artCode

Drag and drop in React with React Beautiful DND

Using react-beautiful-dnd to add drag and drop functionality in your React applications.

Tags

  • Javascript

Published

Reading Time

10 min
Cover image for Drag and drop in React with React Beautiful DND

react-beautiful-dnd is a library created by Atlassian to facilitate the implementation of drag and drop functionality in React applications. This library offers a smooth and accessible user experience, supporting complex scenarios like list reordering. Its ease of use and smooth animations make it an excellent choice for developers who want to improve the interactivity of their applications.

Let's assume you have already installed React and the necessary dependent libraries in your project.

Installation

Terminal
// npm npm install react-beautiful-dnd // yarn yarn add react-beautiful-dnd

If you're using TypeScript, make sure to also install the types for react-beautiful-dnd:

JavaScript
// npm npm install @types/react-beautiful-dnd // yarn yarn add @types/react-beautiful-dnd

Once the library and its possible dependencies are installed, let's proceed with a basic configuration by importing the main components

JavaScript
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';

The Drag and Drop context (DragDropContext) is the main component that wraps droppable areas and draggable elements. It manages drag and drop events.

JavaScript
<DragDropContext onDragEnd={() => console.log('attività completata')}> {/* Altri componenti */} </DragDropContext>

Once this step is done, let's proceed with installing a draggable area.

Droppable areas are the zones where draggable elements can be dragged and dropped. The Droppable component manages the behavior and appearance of these areas.

JavaScript
const DroppableArea = () => { return ( <Droppable droppableId="droppable-area"> {(provided) => ( <div {...provided.droppableProps} ref={provided.innerRef}> {/* Elementi Draggable */} {provided.placeholder} </div> )} </Droppable> ); };

In the example above, we use droppableId and provided, but let's discover them together!

  • droppableId is a unique identifier for the droppable area
  • provided contains the properties and references necessary to make the droppable area functional

After completing this step, let's proceed to insert draggable elements.

Draggable elements are the elements that can be dragged within droppable areas.

The Draggable component manages the behavior and appearance of these elements.

JavaScript
const DraggableItem = ({ item, index }) => { return ( <Draggable draggableId={item.id} index={index}> {(provided) => ( <div ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} > {item.content} </div> )} </Draggable> ); };

Here's a complete example of how your component structure should look:

JavaScript
import React, { useState } from 'react'; import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd'; // Elementi iniziali const initialItems = [ { id: 'item-1', content: 'Item 1' }, { id: 'item-2', content: 'Item 2' }, { id: 'item-3', content: 'Item 3' }, ]; const App = () => { const [items, setItems] = useState(initialItems); // Funzione per gestire la fine del drag and drop const onDragEnd = (result) => { if (!result.destination) return; const newItems = Array.from(items); const [removed] = newItems.splice(result.source.index, 1); newItems.splice(result.destination.index, 0, removed); setItems(newItems); }; return ( <DragDropContext onDragEnd={onDragEnd}> <Droppable droppableId="droppable-area"> {(provided) => ( <div {...provided.droppableProps} ref={provided.innerRef} style={{ padding: '16px', width: '250px', backgroundColor: '#f0f0f0', }} > {items.map((item, index) => ( <Draggable key={item.id} draggableId={item.id} index={index}> {(provided, snapshot) => { return ( <div ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} style={{ userSelect: 'none', padding: '16px', margin: '0 0 8px 0', minHeight: '50px', backgroundColor: snapshot.isDragging ? '#e0e0e0' : '#fff', color: '#333', ...provided.draggableProps.style, }} > {item.content} </div> ); }} </Draggable> ))} {provided.placeholder} </div> )} </Droppable> </DragDropContext> ); }; export default App;

This library offers various advanced features for complex scenarios:

  • Nested Lists Management: supports drag and drop within nested lists
  • Smooth Animations: integrated animations improve user experience
  • Accessibility: supports accessibility for users using keyboard or screen readers
  • Complete Callbacks: uses callbacks like onDragStart, onDragUpdate, and onDragEnd to customize drag and drop behavior

react-beautiful-dnd is a powerful and easy-to-use library for adding drag and drop functionality to React applications. With its wide range of features and support for complex scenarios, it's an excellent choice for improving the interactivity and user experience of your applications.

Try it in your next application and experiment with its potential!

Drag and drop in React with React Beautiful DND | artCode