Latest Tutorials

Learn about the latest technologies from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

How To Drag and Drop Files in React Applications with react-dropzone

Adding files to upload is a common task in React applications. In this article you will learn how to easily add a drop zone for files in React projects with react-dropzone. We will see how to add react-dropzone to a project, configure and apply styling to your drop zone.The react-dropzone allows to create drag-drop zones for files in React applications. You can add files by dropping them or via a file dialog. For this article, we assume that you're familiar with React components and how to use props and state to control them. Let's start by adding react-dropzone to a project: Now we can use the Dropzone component from the react-dropzone package to add a drop zone for files. We will show a list of added files in a list: We start by importing the Dropzone component. Next, we use it to render our drop zone for files. We specify the handleDrop handler that will process dropped files with the onDrop property. Also, we specify a function as the Dropzone component children that renders a drop zone. This function receives two arguments: getRootProps and getInputProps . These functions return properties that should be applied to drop zone elements. The Dropzone component helps us to create a drop zone but we are free to render any layout we want. The only requirement is to apply properties returned by getRootProps to a root element and apply properties returned by getInputProps to an <input> element. If we want to specify additional properties to root or input elements, we need to pass them to props functions. In our example, we do so by specifying the value for the className property to the getRootProps function. This is required to ensure that properties do not get overridden. When we add files to a drop zone, the handleDrop handler will be called. We use the useState hook to store names of added files in a state. We use the fileNames state variable during render to display a list of added files. In this article, we'll be using the Dropzone component for drop zones. If you prefer working with hooks over components, you may use the useDropzone hook to achieve the same functionality. The Dropzone component is just a wrapper over the useDropzone hook that makes it easier to use react-dropzone. The react-dropzone provides configuration options that allow controlling the behavior of a drop zone. You can check out the API description to review available options. We can configure a drop zone to accept single or multiple files, specify a minimum and maximum size for files to accept, limit accepted files by MIME type or extension, and get notified about dragging events. Let's configure a drop zone to accept only image files between 10 Kb and 3 Mb: We specify additional properties for the Dropzone component to configure our drop zone. The minSize and maxSize properties specify a minimum and maximum file size, and the accept property allows to specify types of files to accept. It is up to you to style a drop zone when using react-dropzone. The react-dropzone does not provide any default styling. However, it makes it easy to dynamically apply styles depending on a drag-drop events. You can define your styling to match the design of your application. For example, this is the CSS class for a drop zone that we've used in previous examples: To dynamically apply additional styling, we may use properties provided to the rendering function in the Dropzone component. Let's change the border of a drop zone depending on whether files will be accepted by the drop zone: In this example, we're using the isDragActive , isDragAccept , and isDragReject properties provided to the rendering function to change the look of a drop zone. When a file complies with a drop zone configuration (in our case, image file with a specific size), the isDragAccept property will be true . If a file will not be accepted, the isDragReject property will be true . The isDragActive property will be true while user drags files over a drop zone. The react-dropzone is an easy way to add a drop zone for files in your React applications. It is easy to use and provides a lot of configuration options.

Thumbnail Image of Tutorial How To Drag and Drop Files in React Applications with react-dropzone

Wonders of React D3 – How to get started!

📰 In this post, we will take a close look at D3, and how it enables us to visualize data. Furthermore, we’ll take a brief look at ways to combine React and D3, and finally use one of those methods to display and update a simple dataset.ReactJS is a powerful UI library that many developers turn towards these days to create fast, snappy and complex user interfaces, and it continues to grow into a more mature and robust solution for implementing user interfaces day by day. Meanwhile, whenever developers have to deal with data visualization, oftentimes their immediate go-to JavaScript library is none other than D3 (short for Data-Driven Documents). Assuming we have to create a user interface that is powered by data manipulation, using both of these libraries in conjunction can potentially solve many problems. So, let's outline several methods for you to implement D3 with ReactJS to create those high-end data-driven user interfaces you are looking for! Before we dive headfirst into React D3, it is better to have some know-how of ReactJS to make it easy for you to absorb all the information in this post. Since this is not a ReactJS tutorial, we would recommend you check out the official React docs to get a basic understanding. To get a thorough front to back understanding of React, you can always get the Fullstack React book . As we established earlier, D3 is one of the most widely used JavaScript libraries for data manipulation and visualization. D3 works at a lower-level to allow users to create a visual representation of the dataset at hand. Now, one may wonder what it is about D3 that makes it the best at what it does. In essence, D3 makes use of HTML, CSS and SVG elements as the core building blocks for visualization, and offers complex methods to empower our UI to handle different types of datasets. Not only that, as developers we’re given complete control over the outlook and handling of the elements we create. Varying from dataset to dataset, there is not a single solution that we can use to extract the most useful insights through visualization, therefore D3 gives us the freedom to shape and manipulate our visualizations as needed. Firstly, we use D3 to load the data using select() or selectAll() depending on how many elements we want to connect. Next, we use data() to bind our dataset to those DOM (Document Object Model) elements. Once connected, we can update the DOM elements based on changes in the data. This process is called "Data Joins" . Once connected, we can use any modification methods, such as text() , and create a custom render function that will map and render our data values to elements. If we have more data values remaining, we can call the enter() function, and append() new dynamic elements to map the rest. Finally, if we would like to dynamically remove any of those elements, we can call the exit() function, and then remove() the required elements. The following code outputs a list of paragraphs using the data items provided in the data variable, by mapping three of the data values to the existing tags and then appending new <p> elements to the container <div> In this method, we tell D3 exactly what we want and let it handle the rest for us. D3 also provides us with a lot of different utilities, such as transitions, brushes, and polygons to make our visualizations highly customizable. Both React and D3 have amazing capabilities to access and modify the DOM. However, when we want to implement D3 within a React application, it is very important to figure out a way to modify the DOM in such a way that both libraries do not clash with each other. To circumvent this issue, there are a number of ways of integrating React and D3. Let's take a brief look at how each implementation works. In this approach, we give complete control of mutating the DOM to D3. This is done by using refs and giving D3 direct access to modify that DOM element. In our React component, we modify the componentDidMount and componentDidUpdate lifecycle methods to enter , update and exit the subject element, SVG in our case. This approach is very useful if we already have a D3 implementation that we want to use in our React code. However, due to the fact that D3 has complete control and we're not using React to modify our elements, our code may not follow "The React Way" of doing things. That does not mean that we can't use state though. In fact, we can isolate our D3 logic in multiple React components, play with the state of those components and integrate them into a larger React web page. Nicolas Hery describes this approach in detail on his blog . In essence, this approach allows us to utilize React lifecycle methods to sync our D3 calls. For example, we will: This is done within class-based components, by encapsulating our D3 code within an object that handles all of the D3 logic and calling that object within our React component. This is the approach that follows "The React Way" . What this means is, we will let React handle the rendering, and only use D3 for computation. Therefore, we can create functions for our D3 computations, such as for calculating scales and ranges, etc. These functions are then called within the render method of a component to dynamically create and update those elements. This approach enables us to fully utilize React when working with D3, and as such we are responsible for creating our own shapes and animating them. Therefore, we're free to use any React libraries such as react-spring for animation. Since it requires us to utilize low-level D3 concepts, it is not preferred for complete beginners to start with this method. Let's create a simple D3 visualization to show rectangles of various sizes using the first approach: Giving D3 complete control. We will look at two ways to do this, using class-based components and then looking at the React Hooks implementation to compare the differences. You can use the following command in the command line to get a minimal boilerplate set-up for React. npx create-react-app d3React This will create a folder 'd3React' , and install all the required dependencies. Next, you need to install the D3 NPM package. For that, you can use the following command, npm install d3 Now that everything is installed, you can empty the App.js file, and start writing your own code. Within App.js , you can simply import and display a new component that will be created next. This is what the file should look like, In the newly created RectClass.js file, we can start sprinkling D3 into our React code. Let's start with the following, In the code above, you will firstly return an empty SVG and create a new ref for it so that we can reference that DOM node within our React code. Now, we know from earlier that to dynamically update content using D3, we need to enter() , update() and finally exit() . To handle create and update, you will call the createSvgContainer() method in both componentDidMount and componentDidUpdate . Within createSvgContainer() , you will execute the following code: This will let you select the SVG dom element using D3, and target the "rect" sub-elements. Next, you will perform a join by synchronizing the small dataset (stored in the state) using data() . Now that we have a selection, we can use that to enter() using D3, and perform the necessary changes in attributes and utilize all the functions D3 provides us with. As an example, you can create rectangles inside the SVG, apply some styling to those rectangles and set the height and weight to a calculated value. Now that the attributes are defined, we would like to apply when entering or updating elements, let's define a way to remove elements using D3. The end result is going to be an SVG with a few boxes having blue borders. Now that you have newly created elements, you can start to update them or remove them. To do this, let's create two new methods in our class component. Our update function creates a new array where each value in the previous array has been added by 5. Meanwhile, our removeLast function does exactly that, it removes the last item from the data array. Now, we need to call these functions somewhere. Let's create two buttons, update and remove that call these functions for us. The updated render method will look like this, Let's do the exact same thing we did above, but instead, use React Hooks and see how they can make our life much easier. The JSX, as well as our update and remove functions, will look quite identical. However, since we're using a functional component, you will not be using lifecycle methods at all. Instead, first, you need to initialize the state with the useState() hook, then assign the SVG ref using useRef() . You will then use the useEffect() hook instead of lifecycle methods, and select the ref, and make changes to it using D3 as we did previously. Notice how we're also utilizing a cool feature D3 allows us to use, which is .join() . Within this function, we can pass functions for all three enter, update and exit phases and perform the required actions to each. Instead of assigning duplicate attributes and styles, we can simply factor out all of those chained functions and append them to the end of our chain. D3 is great to load, manipulate and display data using complex computations. React is great to create highly dynamic and powerful user interfaces. What do you get when you combine them? The answer: A complete solution to create web applications that display multiple dynamic charts, graphs and other types of data visualizations leveraging React state for interaction between and within components. There are many D3 React libraries worth exploring, as well as techniques to make D3 and React work together. It's no secret that to get the best results out of both libraries, you must master the basics of each library individually, and then give a shot at creating breathtaking visualizations!

Thumbnail Image of Tutorial Wonders of React D3 – How to get started!

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More

How to use Bootstrap in React applications with reactstrap

In this article we will see how to use the Bootstrap UI framework in React applications using reactstrap. You will learn how to add Bootstrap to a React application, use Bootstrap components, and style your application with Bootstrap themes.Bootstrap is a popular front-end component library. It helps to build web applications using a set of prebuilt components. It also provides a responsive grid system and theming support. Bootstrap components are a mix of HTML, CSS, and JavaScript with additional dependencies like jQuery. This makes them hard to use in React applications. The reactstrap library provides a React implementation of Bootstrap components with no dependency on jQuery. With reactstrap, we can easily use Bootstrap components as usual React components. For this article, we assume that you're already familiar with React components. There is another popular library that implements Bootstrap components in React, which is React Bootstrap . Both libraries, reactstrap and React Bootstrap, keep good parity with Bootstrap components and provide a similar approach to components. Both libraries would be a valid choice as a way to add Bootstrap components to your React application. Here are some points that may help you to select between the two: Let's start by adding reactstrap to a project: Components in reactstrap do not include CSS, they use Bootstrap CSS instead. This is great as it allows us to reuse Bootstrap themes to style React applications. We need to install Bootstrap too as we're going to use standard Bootstrap CSS file from it: Now, we can use reactstrap components in our project: This demo shows three different buttons using the Button component. We start by importing standard Bootstrap CSS. Next, we import Button component from the reactstrap package. Finally, we use Button to render buttons. Here is a step-by-step guide to adding any reactstrap component to a React project. We can start by looking for a component we want to use among a list of components on the reactstrap site. For every component, there is a description, demo, and API description available. Once we've found the right component, we can import it to a project and use it. For example, let's add the Toast component: We import the Toast component from reactstrap. Also, we import ToastHeader and ToastBody components that are used to declare toast's header and body respectively. Additionally, we leverage useState React hook to control the visibility of our toast. The isOpen property of the Toast component defines whether to show it. The toggle property of the ToastHeader component accepts a function that will run when a user tries to close the toast. Components from reactstrap do not define their own CSS and rely on the Bootstrap CSS. That means that a styling approach for components is the same as for standard Bootstrap components. We can apply an existing custom theme or create our own. For example, let's define a new custom.scss file with the following content: In this file, we override default values for Bootstrap background and primary colors. Also, we import the standard Bootstrap CSS file to get all the default styles. Now, we can use this custom.scss file in our application instead of the standard one: This example is identical to our first demo with three buttons. However, instead of the standard Bootstrap CSS file, we import our custom.scss file. This affects the background and primary colors. Using reactstrap we can quickly add Bootstrap to a React application. We can use ready to use components to quickly build and leverage Bootstrap themes to adjust the style of our React applications.

Thumbnail Image of Tutorial How to use Bootstrap in React applications with reactstrap

How to Add Date Picker in React with react-datepicker

In this article we will see how to add a date picker in React applications with React Datepicker. We will learn how to use a date picker component in a React project, how to localize and style different date picker elements.Selecting a date is a popular task in React applications. We may use a date picker component when filling out forms, selecting a date for a filter, or creating an event. React Datepicker is a highly customizable component that makes it easy to add a date picker component to a React project. For this article, we assume that you're familiar with React components, and how to use props and state to control them. Let's start by adding React Datepicker to a project: Now we can use React Datepicker in our application to display a date picker: We start by importing DatePicker component from the react-datepicker package. We also import react-datepicker.css stylesheet file for basic CSS styles. Finally, we use DatePicker component to render a datepicker. We specify the date to display with the selected property. We also specify a handler for a date changing with the onChange property. The React Datepicker component provides loads of configuration options. This allows covering lots of scenarios where users need a date picker. With properties we can change the functionality of a date picker, modify localization settings, and style the component. To learn about available configuration options, you can check out a list of examples on the official website or look at the properties of the component . For example, let's allow to select a date between today and 3 days in the future. Also, let's add an ability to select a time: To limit a date selection range we specify minDate and maxDate properties. To display a time selection pane we specify the showTimeSelect property. We also specify the dateFormat property to specify a custom date format to include the selected time. React Datepicker support localization of a date picker component. It relies on the date-fns package for that. You can specify a locale either globally or for each date picker. Let's add a Spanish locale for a date picker: First, we import es locale object from date-fns . We also import the registerLocale helper function from the React Datepicker. Next, we load the imported locale object with the call to the registerLocale function. Finally, we specify the locale property of the DatePicker to specify the locale for a date picker component. Alternatively, we could specify the default locale globaly for all date pickers with the setDefaultLocale("es") function. The React Datepicker component can be styled according to your application requirements. There are several approaches available for that. If you want to modify some functionality and not only styles you can use the customInput property to define a custom React component for a date input, renderCustomHeader for a custom header rendering function and renderDayContents for a custom day rendering function. If you need to style only a specific element of a date picker, you can use one of the properties exposed by DatePicker to define a custom class. There are calendarClassName , dayClassName , timeClassName and popperClassName props available. Using these properties you can also apply a dynamic styling by specifying a function as a prop value. The function should return a class name depending on an element value. If you want to create a custom theme for a date picker you can override standard CSS styles. This way you can style every element of a date picker in a way you want. Here's an example that applies custom CSS theme, defines a custom input component, and applies styling for the first five days of each month: In this example, we show all the styling approaches described. Instead of the standard CSS file, we import custom.scss file that overrides the font family, font size, and a color for the selected date. The customInput property is used to define a custom input component. The dayClassName is a property that allows specifying a custom CSS class name to a specific day. React Datepicker provides a highly customizable date picker component that can be used in React projects. We can customize the functionality of a date picker, apply custom styling, and localize different parts of the component.

Thumbnail Image of Tutorial How to Add Date Picker in React with react-datepicker

Using componentDidUpdate in React

In this article we will see how to use the componentDidUpdate function in React components to respond to changes. This can be external changes in a parent component or internal changes in a component’s state. We will see how to use the componentDidUpdate function to access DOM nodes and fetch data from a server.For this article, we assume that you're already familiar with React components, and how to use props and state to control them. The componentDidUpdate function is a part of a React component’s life cycle. It is called when a component got updated. This might happen if new props have been provided by a parent component or an internal state has been changed. The componentDidUpdate gets called after a render, which means that we can access DOM nodes in it. This function receives previous props and state as parameters. It can also access new props and state with this.props and this.state : There are several scenarios where the componentDidUpdate function may come in handy. The first scenario is when you need to access underlying DOM nodes of React components. Using DOM nodes we can get our component's position and dimensions, or initialize an animation. We can also pass the underlying DOM node to 3rd party non-React libraries that manipulate DOM. Here’s an example in which we update the size of a green box every time a user clicks the "Resize" button: In this example, we’ve got a component that stores the size value in its state. Every time a user clicks the "Resize" button, handleIncrementClick click handler increases the size by 10 and updates the state with the setState function. This causes the component's update. The componentDidUpdate function will run every time a component updates. That is, every time a user clicks the button and the setState function got called. In the componentDidUpdate we get the ref to the div DOM element and directly set its width and height. Another popular scenario is when you need to request data from a server or remote API due to changes in component’s props . As an example of fetching data from a server, let's show a list of projects for a selected user. A name of a user will be selected with buttons, while a list of user's projects will be fetched from a server. First, let's take a look at the parent MyComponent component. It shows two buttons for selecting users and the ProjectsComponent component that will show a list of projects. We will get to the ProjectsComponent implementation in a minute. In this example, we’ve got the MyComponent parent component that stores client name in its state and pass this value to the child ProjectsComponent . When the client value changes the ProjectsComponent will receive new props which will cause an update. Now, let's take a look at the implementation of the ProjectsComponent that shows a list of projects for a selected user: In the componentDidUpdate we check whether a client’s name has changed by comparing values in prevProps and this.props . If the client has changed, we request a list of their projects from a server (function fetchData emulates fetching from a server with a timeout). Once we’ve received the remote data, we update a component’s state with a list of projects. It is important to note that updating the component's internal state will trigger a new update with new render and the componentDidUpdate will be called again. We need to be careful with the setState function in the componentDidUpdate as it may cause an infinite update loop. In our case, we check the name of a client in props to avoid that. There is one more scenario where componentDidUpdate is used. It is related to the getSnapshotBeforeUpdate function, which is another life cycle function of React components. The getSnapshotBeforeUpdate function is called right before the DOM update. It receives previous props and state as two arguments. In this function, we can capture the state of DOM nodes before an update. The returned value from the getSnapshotBeforeUpdate function will be passed as the third argument to componentDidUpdate along with previous props and state. This way, we can compare a DOM node value before and after an update and apply additional logic as needed. For example, let's display a list of items. When there's a lot of items in a list, users can use a scroll: The List component has got the items property which is used to render a list of items. In our parent MyComponent component, we pass items from the state to List component. Note how scrolling behaves in this example. When we add new items, it stays in the same place. To view newly added items we need to manually scroll down. This is because the ul DOM element that React uses to display items stays the same after an update including a position of a scrolling pane. We need to use getSnapshotBeforeUpdate function and componentDidUpdate to change scrolling behavior. Let's implement a list component that will control its scroll position when new items got added: In this example, we have got the ListWithScroll component that returns the scroll position from the getSnapshotBeforeUpdate function right before the DOM node update. The componentDidUpdate function receives that value as the third parameter. We use that snapshot value to amend the scroll position of the ul DOM node after the update. You can see in this example, how a usual list and a list with scroll support work. By adjusting a scroll position we allow users to see newly added items without additional manual scrolling. If you want to optimize the performance of your component, there is the shouldComponentUpdate function that is being called before an update. By default, it returns true to confirm that an update should occur. You can override this function and return false if an update is not required. React will take the result of shouldComponentUpdate into account. The shouldComponentUpdate function receives values of next properties and next state as arguments. We can use this.props and this.state to access current properties and state. If React decides to skip the update for a component, the didComponentUpdate will not be called: In this example, we're checking the name property to define whether a component should be updated. We can also use the React.PureComponent as a base class for a component instead of implementing the shouldComponentUpdate function. This class is similar to the React.Component class that we usually use as a base class for components. The difference is that React.PureComponent implements shouldComponentUpdate . It performs a shallow comparison of props and state to define whether an update is needed. A shallow comparison means that it takes all properties of props and state objects and checks that next and current values are strictly equal. In this example, we inherit our component's class from the React.PureComponent instead of React.Component . We don't need to implement the shouldComponentUpdate function as React.PureComponent does that. The component will check its props and state in its shouldComponentUpdate implementation to define whether an update is required. If component's props and state haven't changed, componentDidUpdate will not run. The componentDidUpdate is a part of a React component life cycle. We use it to react to external changes in component's props or internal state changes. With the componentDidUpdate you can modify the underlying DOM nodes, request remote data, and update the internal state of your component. Here are additional resources that will help you to learn more about componentDidUpdate and React component's life cycle: