React Beautiful Dnd

Learn via video courses
Topics Covered

Overview

As a user, you must have noticed the drag and drop (that is when you click an object and move it to another place) functionality in different applications, be it web apps or system applications. This functionality has its advantages (user-friendly, increases interactivity, etc), and you should add it as a developer in your web app for a better user experience which will lead to an increase in the popularity of the web application.

Introduction

In modern web applications, there are a lot of functionalities that are used to make the user experience good, and one of them is drag and drop. React Beautiful dnd is a library that lets you incorporate this functionality into your application.

What are Drag and Drop?

Drag and Drop, as the term suggests, is the functionality where you can click an item to drag it and then drop it someplace, and as a result of this, you will see some effect.

Applications where you need to prioritize tasks and establish an order for how they should be completed, such as checklists or project management dashboards, frequently use this effect.

Although drag and drop can be used in more complex situations, we will limit our tutorial to simple list functionality.

what-is-drag-and-drop

What is React Beautiful DnD?

React-beautiful-dnd is an open-source library created by Atlassian(the same team that created Jira). It makes it simple for web developers to incorporate drag-and-drop capabilities into their applications. If you want to build a drag-and-drop functionality on your website, react-beautiful-dnd is the way to go, as it is currently the most well-liked drag-and-drop package in the React community.

Let's examine some of react-beautiful-dnd's key characteristics to see why it is so well-liked.

  1. It is quite adaptable. Since the library strives to remain as minimal as feasible, the animation just has a few simple stylings. They are modifiable and replaceable with your style. Even without using a mouse, you can implement your custom sensors to operate the drag-and-drop lists using a keyboard or other input devices.
  2. Because no new DOM nodes are formed, establishing the layout is straightforward and predictable, allowing you to effortlessly build your drag-and-drop components and lists.
  3. In addition to the first point, react-beautiful-dnd offers a variety of options and metadata that enable you to utilize it for countless combinations and use cases.

Using React-Beautiful-Dnd Components for Drag-and-Drop Functionality

Because the library is tightly integrated with the React environment, all functionality is created and managed around essential React elements.

DragDropContext

All of the details regarding your drag-and-drop lists are contained in this context. You must use this element to encapsulate everything associated with drag and drop if you want it to function properly because it is dependent on the React context. The main callback for managing the data of your lists is the onDrag method, which is another option that is accepted. Later, we shall go into more detail.

Droppable

Your list is included in this element, along with the drop zone that serves as the source whenever elements are dropped. It must be enclosed in a function that returns a React element, and it must be given a droppableId. With a few internal parameters and a snapshot parameter providing details about the list's current state, this function is called. This can be applied to style the element or serve as a callback for events that revolve around it.

Draggable

Each list element is included within this. Every single item on your list needs to be enclosed in this element. The Children element is a method that is invoked with the Snapshot attribute, just like the Droppable element is.

draggable

React Beautiful Dnd Example

We will be creating a simple list with the drag and drop functionality to demonstrate react beautiful dnd.

Building a Drag-and-Drop List with React-Beautiful-Dnd

Step - 1: Setting Up a New React.js Application

First, we will create a new React.js app with a simple list containing items.

Use the following command to create a new React.js app.

Then use the following command to go to your project folder.

In the app.js file, we will first create an array of objects and then loop through them to display on the web page.

Step - 2: Installing react-beautiful-dnd

Use the following command to install the library in your project.

Alternatively,

Step - 3: Setting Up Drag and Drop Elements in the Application Using react-beautiful-dnd

First, you need to import DragDropContext from the react beautiful dnd library:

Similar to the React Context API, the DragDropContext lets you access the component tree so that you can use the React Beautiful dnd library.

You must ensure that your DragDropContext encompasses all of those items, such as in the root of your application if you intend to add drag and drop to more than one list. DragDropContext cannot be nested.

DragDropContext should be used to enclose our list.

The next step is to establish a Droppable region, which will enable us to designate a certain space inside which our items can be moved.

Similar to DragDropContext we need to import Droppable also

Since we want the whole <ul> list to be droppable, we will wrap all of it with the Droppable component.

This time, however, you will note that we wrapped it slightly differently. First, we provide our Droppable component with a droppableId. Within that component, we are also instantiating a function that accepts the provided argument. Although we would not be utilizing it in this example, this function can accept two arguments, including a snapshot argument.

The input given contains data and citations for the code that the library requires to function correctly. Let us add it to our list element so we may use it:

By doing this, a reference (provided.innerRef) will be created that the library can use to access the HTML element of the list element. Additionally, it adds props to the (provided.droppableProps) element, which enables the library to keep a record of the motion and location of the elements.

The last step in enabling our list with the drag and drop feature is to wrap each list item in the Draggable component.

We will be utilizing the Draggable component, which, like the Droppable component, has a function where we can send extra information to the components of our list items.

Just like DragDropContext, Droppable we need to import the Draggable component in our file.

Next, let us include the draggable component and its top-level function inside our loop to enclose the returned list item.

Since, in the loop, we have a new top-level component, we will shift the key prop out of the list element to the Draggable component:

A draggableId and an index are two additional props that must be specified on the Draggable component.

Then, we will need to add those props to our component after adding the index as an input to our map function:

Last but not least, we also need to pass props to the elements of our unordered list.

We need to add refs to our list elements and using the spread operator we will spread some props that we get from the provided argument:

On testing this drag-and-drop feature we can see that the bottom of the webpage seems a little disorganized as we start shifting items around. We observe a problem of overflow with items on our list.

You will see that react-beautiful-dnd is also alerting the developer console to the fact that we lack a placeholder.

We must also include a placeholder item as part of the specification of React Beautiful DnD.

The purpose of this, which they offer right out of the box, is to take up the area that the object we are moving now occupies.

To do that, we need to add provided.placeholder to the component of our Droppable top-level list that is at the bottom of our unordered list tag:

Now if we start moving list items, we notice that the content remains in its proper place and our page flow is unaffected.

Step - 4: Managing List State After Drag and Drop with React Beautiful DnD

Whenever we shift our objects, they briefly remain where they are dropped. However, our component tree will update once react-beautiful-dnd has completed its work.

Since we have not saved our list outside of the react beautiful dnd's memory, the items regain their original position in the list on component rerender.

To fix this, DragDropContext accepts an onDragEnd prop, which enables us to call a function once we drag any item. To update our state for the subsequent render cycle, this function accepts arguments from us that include the revised order of our items.

So we have to include the useState hook from react, and then we need to create our default character list.

Write the following code at the top.

Then write:

We should now alter the array we are mapping through to our new state as we will be upgrading it to supply items of the list and their order:

Since we now have a state, we can change it whenever we drag an item from the list.

OnDragEnd is a prop that is passed to the DragDropContext component. When someone quits dragging an item within the list, a function will be called.

Now we will include the handleOnDragEnd method as a prop:

Now we have to declare this handleOnDragEnd function.

Initially, we are copying the character array to an array named items. Now we locate the element in our items array by using the source.index value and use the splice function to remove the item. After splicing we get a destructured result. We get an object called reorderedItem in which we have the dragged item. Then, once more employing the splice method, we include that element back into the array using our destination.index, but at its new spot. The updateCharacters function is our last step in updating the state of our characters.

Now that we have created our method, we can drag the characters around while they continue to remember where they are.

Step - 5: Solving the Issue of Dragging Items Out of Bounds

One problem with our implementation is that we get an error if a person does not drag the item precisely inside our designated containers.

The problem is that we do not have a destination when we drag it beyond the specified container.

To prevent this, we can just add a line of code that, before moving our item, checks to see if the destination is already in place and, if not, exits the function:

Now when we try to drag the item out again after refreshing the page, it returns without a problem to its original position.

Conclusion

  • Drag and Drop as the term suggests are the functionality where you can click an item to drag it and then drop it someplace and as a result of this you will see some effect.
  • react-beautiful-dnd is an open-source library created by Atlassian.
  • DragDropContext, Droppable, and Draggable are the different components required to add this functionality.
  • All of the details regarding your drag and drop lists are contained in DragDropContext.
  • Your list is included in Droppable, along with the drop zone that serves as the source whenever elements are dropped.
  • Each list element is included within Draggable.
  • You need to make use of the useState hook and perform operations on the state so that the changes in the list can be visible, or the list elements will regain their original positions once you stop dragging the elements.