Drag and Drop sortable list in React

In this article, we will show you how to implement drag and drop sortable list in React. If you have a list of any elements and you want to implement sorting using Drag and Drop then we’ll look at this simple way to implement it using NPM Package with an example in this article.

Demo Application

Output - Drag and Drop sortable list in React - Clue Mediator
Output – Drag and Drop sortable list in React – Clue Mediator

Drag and Drop sortable list in React

  1. Install NPM dependencies
  2. Create sortable container and element
  3. Render sortable list
  4. Output

1. Install NPM dependencies

Here we will use the react-sortable-hoc npm package to implement a drag and drop sortable list. Run the following command to install the package.

We’ll use one more package array-move to move an array item to a different position.

2. Create sortable container and element

To start the example we will render the following list on page.

Let’s create a sortable container and element using the react-sortable-hoc package where we’ll wrap the component using the SortableElement and SortableContainer.

SortableItem.js
SortableList.js

3. Render sortable list

Finally, we can use the SortableList.js to render the sortable list and change the index of the item using the array-move package on the onSortEnd event.

App.js

After sorting the list, you’ll get the final result in the state variable.

4. Output

Run the application and check the output in the browser.

I hope you find this article helpful.
Follow and Subscribe us for more update. Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

3 Responses

  1. John Woodcock says:

    This is a great tutorial and my list is sorting as expected. However, I’m trying to add a delete button to the items in the list.

    Basically, the delete button filters out the target and updates the state list. The state list is getting updated properly but the SortableList is removing the end item instead of rebuilding the list with the new state list.

    • Clue Mediator says:

      Hi John,
      I am just removing the item from the state list and it’s working.

      Can you please share your code?

  2. Leandro says:

    Good job! I have a question. How can I sort elements from differents list? I mean, drag items from list one to list two. Please help me.

Leave a Reply

Your email address will not be published. Required fields are marked *