React DnD (Drag and Drop)

Topics Covered

Overview

Drag and Drop is a common interaction technique in which the various UI elements of an application can be dragged from one place and dropped to the other. React drag and drop is most frequently used for uploading files, moving objects between lists, and rearranging assets and images. We'll concentrate on a variety of implementing drag and drop in React tools and application cases in this tutorial.

What are Drag and Drop?

Drag and Drop is a functionality that is responsible for choosing an object or a chunk of text, dragging it to the desired area, and then “dropping” it there. As a result, it is an interaction that enables someone to click on anything, drag it to another location, and dump it there—often with an unintended consequence for the app.

The functionality is often used in applications where you need to prioritize tasks and establish an order for how they should be completed, such as to-do lists or project management dashboards, frequently use this effect.

Libraries in React Drag and Drop

The three most popular libraries are used to implement the drag and drop feature in React which are as follows.

  • React-beautiful-DnD:
    It is an accessible drag-and-drop library by Atlassian which is known for its accessibility, and a powerful API.
  • React-DnD:
    It is used to create advanced drag-and-drop interfaces by keeping the components decoupled.
  • React-Grid-Layout:
    It is a draggable and resizable grid layout with responsive breakpoints.

All these libraries are very popular among react developers and have been explained further with their advantages and disadvantages.

What is React Beautiful DND?

React Beautiful DnD is a drag-and-drop library from Atlassian. It is a higher-level abstraction created exclusively for lists. It is intended to provide a seamless, lovely, and accessible drag-and-drop React experience. It is built to offer drag-and-drop functionality while keeping accessibility in mind, as well as to maintain it fast and reliable with a strong API.

Advantages of React Beautiful DnD

  • It is beautiful and provides a natural movement of the items.
  • It works well with one-dimensional layouts and drag-and-drop features that require a horizontal or vertical movement of the items.
  • It is a clean and powerful API that is simple and does not add any complexity to the codebase.
  • It provides accessibility with a powerful keyboard and screen reader support.

Disadvantages of React Beautiful DnD

  • React Beautiful DnD does not work for grids as the elements will be moving in all directions.
  • It is not able to calculate the position of the X and Y axis at the same time.
  • Due to this, the content is displayed randomly in any order until it is dropped somewhere on the screen.

Implementing React Drag and Drop

Now, we will be learning how to implement the drag-and-drop feature using react-beautiful-dnd.

First of all, let's install the library using the below command.

Now, let us see the actual code to implement the drag-and-drop feature of react-beautiful-dnd.

Output:

implementing-drag-and-drop-in-react

Explanation:

Firstly, we have wrapped our entire app within the DragDropContext component. This is what the official documentation suggests to us. It is needed to use the drag-and-drop feature provided by react-beautiful-dnd. The DragDropContext component requires an onDragEnd callback which is called once the element is dragged.

After this, we imported the Droppable component which defines the area where the element will be dropped. The Droppable component requires a property called droppableId that is used to specify which specific droppable area we are talking about as the app can have multiple droppable areas. It can be anything as long as it is a string, we have named it items.

Also, the Droppable component needs a function provided which has three important properties. The first one is the provided.innerRef, the second is provided.placeholder which creates a placeholder space while you are dragging the element around, and the provided.droppableProps which is a spread operator and contains all the data and styling.

Now, similar to the Droppable component, we also need a Draggable component that simply makes our elements draggable. It also needs the same id and provided function similar to the Droppable component.

Now, we are looping on the box array we have created which is supposed to be dragged and dropped based on the user's activity. Also, for saving the drag and drop activity, we have used the useState hook.

Practical Examples

How to Upload Files Using React Drag and Drop?

Now, let us see how could we upload files using React Drag and drop. We will be using an in-built library react-dropzone for this purpose.

The React-dropzone library hides the file input and gives it a beautiful dropzone area. Clicking on the dropzone area lets the react-dropzone library launch a file selection dialogue using React ref through the hidden input, allowing us to choose and upload files.

To install the library, we use the below command in the terminal.

Now, we will make a new file named Dropzone.js, which will transform a standard content area into a dropzone area where you can drop files, and then continue.

Below is the code for the Dropzone.js file.

Explanation:

Firstly, we are using the useDropzone hook that exposes some methods and variables to create the custom dropzone area. Now, this hook provides three properties in which we are interested.

One is the getRootProps which determines the height and width of the dropzone area. The second is the getInputProps which allows us to support the click events in addition to the dragging events of our files and the third one is the isDragActive which is set if the files are dragged above the dropzone area and will be very useful to make the styling based on this variable.

Since we are concerned with only uploading the image files in our project, therefore, we have used the accept prop.

Now, let us see what our App.js files would look like.

In the App.js files, we have simply used the Dropzone component. It will display the files that you have dropped in the console.

Now, let us add some styling to make the UI of the page attractive. Add the below code in the index.css file of your project.

Output:

uploading-images-in-react

The file uploaded in the console appears like this below.

file-uploaded-in-the-console

Display of Image Preview

Now, let us see how to display the preview of the images that have been uploaded.

For doing so, we have created a new file called ImageList.js and a new component. Below is the code for the same.

Explanation:

We are rendering individual images using the DisplayPreview component and returning the list of files using the ImageList component.

Also, now we have to add this ImageList component to our App.js file. Below is the code for the same.

Output:

display-of-image-preview

Advantages of React DnD

  • It allows you to build advanced drag-and-drop interfaces by keeping the components decoupled.
  • It works well for both grids and one-dimensional layouts.
  • It has a very powerful API for adding any customizations to the drag-and-drop feature in React.
  • It is extensible and testable.

Disadvantages of React DnD

  • For small projects or examples, the API is very easy to start with. However, it is quite complicated to add complex customizations.
  • Some hacks need to be used to support both web and mobile devices.
  • The learning curve is higher than react-beautiful-dnd.
  • It is more complex than react-beautiful-dnd.

React Grid Layout in React DnD

React Grid Layout is a powerful React library that enables the user to with complete control over the layout. The widths of the columns and rows as well as the locations of the cells inside the grid are all customizable. It is a library that has been exclusively created for React and offers a recognizable component-based API. Moreover, it doesn't need any extra dependencies like jQuery.

React Grid Layout is responsive and enables breakpoint layouts, which may be specified by the user or automatically produced, unlike comparable systems like Packery and Gridster. In case, the developer does not specify the breakpoint for the elements of a website then the React Grid Layout library automatically adjusts the content based on the screen width of the device, therefore placing certain content on one line and shifting the rest on the other based on the screen width of that device.

It works quite well for complicated grid layouts requiring drag and drop, such as dashboards with complete customization and resizing, such as data visualization products, etc. However, for large-scale applications, the complexity of React Grid Layout is worthwhile.

Some of the disadvantages of the React Grid Layout are that it requires a lot of calculations to be performed on your own which makes it an unattractive API. Moreover, React-Grid-component Layout's API, which is required to specify the layout structure in the UI, adds a layer of complexity.

React Native DnD

React provides ample libraries to implement the drag-and-drop functionality on websites but with React Native, the scenario is quite different. We require both the ability to recognize touch motions and the ability to animate components to make drag-and-drop work on a phone. To implement the drag-and-drop functionality in react native, we use the PanResponder and Animated API libraries and implement the drag-and-drop functionality in react native.

React Native component allows programs to recognize touches and respond to them. It is made using the PanResponder.create() function and comes with several preconfigured methods such as onPanResponderGrant which is triggered in the beginning and by which x and y positions of a list item can be initialized with a default value, onPanResponderMove which is activated any time the program detects a movement like scrolling or dragging, and onPanResponderRelease that is activated once the user has released all of the touches.

The Animated API was created to make animations fluid, effective, and simple to create and maintain. Animated places a strong emphasis on declarative relationships between inputs and outputs, programmable transforms in between, and start and stop techniques for managing the execution of time-based animations.

Conclusion

  • Drag and Drop is a feature through which an item can be dragged from one position and dropped to the other.
  • It is an extremely useful feature in the case of to-do lists, and project management dashboards where we need to shuffle the items based on their priorities.
  • React provides ample libraries like react-beautiful-dnd, react-dnd, react-grid-layout, etc for implementing the drag and drop feature in react.
  • The react-beautiful-dnd is suitable for only one-dimensional layouts as they are not able to calculate the position of the X and Y axis at the same time.
  • On the other hand, react-dnd is suitable for both one-dimensional layouts as well as for grids.
  • We can use the PanResponder and Animated API to implement the drag and drop functionality in React Native.