react-beautiful-dnd implements component drag and drop function

react-beautiful-dnd implements component drag and drop function

A beautiful, portable drag-and-drop list library for React.js. To learn more about the features of react-beautiful-dnd and its applicable users, please refer to the official documentation and Chinese translation documentation.

npm: https://www.npmjs.com/package/react-beautiful-dnd

1. Installation

​ It’s so easy to execute the following command in an existing react project.

# yarn
yarn add react-beautiful-dnd
 
# npm
npm install react-beautiful-dnd --save

2.APi

See the official documentation for details.

3. react-beautiful-dnd demo

3.1 demo1 vertical component drag

The effect is as follows:

demo1.gif

Implementation code:

import React, { Component } from "react";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
 
//Initialize data const getItems = count =>
  Array.from({ length: count }, (v, k) => k).map(k => ({
    id: `item-${k + 1}`,
    content: `this is content ${k + 1}`
  }));
 
// Re-record the array order const reorder = (list, startIndex, endIndex) => {
  const result = Array.from(list);
 
  const [removed] = result.splice(startIndex, 1);
 
  result.splice(endIndex, 0, removed);
  return result;
};
 
const grid = 8;
 
// Set the style const getItemStyle = (isDragging, draggableStyle) => ({
  // some basic styles to make the items look a bit nicer
  userSelect: "none",
  padding: grid * 2,
  margin: `0 0 ${grid}px 0`,
 
  // Background changes when dragging background: isDragging ? "lightgreen" : "#ffffff",
 
  // styles we need to apply on draggables
  ... draggableStyle
});
 
const getListStyle = () => ({
  background: 'black',
  padding: grid,
  width: 250
});
 
 
 
export default class ReactBeautifulDnd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: getItems(11)
    };
    this.onDragEnd = this.onDragEnd.bind(this);
  }
 
  onDragEnd(result) {
    if (!result.destination) {
      return;
    }
 
    const items = reorder(
      this.state.items,
      result.source.index,
      result.destination.index
    );
 
    this.setState({
      items
    });
  }
 
 
  render() {
    return (
      <DragDropContext onDragEnd={this.onDragEnd}>
        <center>
          <Droppable droppableId="droppable">
            {(provided, snapshot) => (
              <div
              //The same element to which provided.droppableProps is applied.
                {...provided.droppableProps}
                // For droppable to work properly it must be bound to the highest possible DOM node provided.innerRef.
                ref={provided.innerRef}
                style={getListStyle(snapshot)}
              >
                {this.state.items.map((item, index) => (
                  <Draggable key={item.id} draggableId={item.id} index={index}>
                    {(provided, snapshot) => (
                      <div
                        ref={provided.innerRef}
                        {...provided.draggableProps}
                        {...provided.dragHandleProps}
                        style={getItemStyle(
                          snapshot.isDragging,
                          provided.draggableProps.style
                        )}
                      >
                        {item.content}
                      </div>
                    )}
                  </Draggable>
                ))}
                {provided.placeholder}
              </div>
            )}
          </Droppable>
        </center>
      </DragDropContext>
    );
  }
}

3.2 demo2 horizontal drag

The effect is as follows:

demo2.gif

Implementation code: In fact, it is similar to vertical dragging. Droppable adds an additional attribute for the order of arrangement, direction="horizontal"

import React, { Component } from "react";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
 
 
const getItems = count => (
  Array.from({ length: count }, (v, k) => k).map(k => ({
    id: `item-${k + 1}`,
    content: `this is content ${k + 1}`
  }))
)
 
// Re-record the array order const reorder = (list, startIndex, endIndex) => {
  const result = Array.from(list);
  //Delete and record the deleted elements const [removed] = result.splice(startIndex, 1);
  //Add the original elements to the array result.splice(endIndex, 0, removed);
  return result;
};
 
const grid = 8;
 
 
// Set the style const getItemStyle = (isDragging, draggableStyle) => ({
  // some basic styles to make the items look a bit nicer
  userSelect: "none",
  padding: grid * 2,
  margin: `0 ${grid}px 0 0 `,
 
  // Background changes when dragging background: isDragging ? "lightgreen" : "#ffffff",
 
  // styles we need to apply on draggables
  ... draggableStyle
});
 
const getListStyle = () => ({
  background: 'black',
  display: 'flex',
  padding: grid,
  overflow: 'auto',
});
 
 
class ReactBeautifulDndHorizontal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: getItems(10)
    };
    this.onDragEnd = this.onDragEnd.bind(this);
  }
 
  onDragEnd(result) {
    if (!result.destination) {
      return;
    }
 
    const items = reorder(
      this.state.items,
      result.source.index,
      result.destination.index
    );
 
    this.setState({
      items
    });
  }
 
  render() {
    return (
      <DragDropContext onDragEnd={this.onDragEnd}>
        <Droppable droppableId="droppable" direction="horizontal">
          {(provided, snapshot) => (
            <div
              {...provided.droppableProps}
              ref={provided.innerRef}
              style={getListStyle(snapshot.isDraggingOver)}
            >
              {this.state.items.map((item, index) => (
                <Draggable key={item.id} draggableId={item.id} index={index}>
                  {(provided, snapshot) => (
                    <div
                      ref={provided.innerRef}
                      {...provided.draggableProps}
                      {...provided.dragHandleProps}
                      style={getItemStyle(
                        snapshot.isDragging,
                        provided.draggableProps.style
                      )}
                    >
                      {item.content}
                    </div>
                  )}
                </Draggable>
              ))}
              {provided.placeholder}
            </div>
          )}
        </Droppable>
      </DragDropContext>
    )
  }
}
 
export default ReactBeautifulDndHorizontal

3.3 demo3 implements dragging of a to-do item (vertical and horizontal dragging)

demo3.gif

The implementation principles are actually similar. The code is organized and placed on github. Address: github

4. Feeling

At present, I have simply used react-beautiful-dnd and it feels very simple to get started, and the API is not complicated. The performance is also good (demo2 rendered more than 170 tasks. Dragging is still as smooth as silk). I will mark any deficiencies I encounter in the future.

This is the end of this article about react-beautiful-dnd component drag and drop. For more relevant react-beautiful-dnd component drag and drop content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of gantt chart draggable and editable (highcharts can be used for vue and react)
  • Typescript+react to achieve simple drag and drop effects on mobile and PC
  • Using react-beautiful-dnd to implement drag and drop between lists
  • More than 100 lines of code to implement react drag hooks
  • React.js component implements drag and drop sorting component function process analysis
  • React sample code to implement drag and drop function
  • React.js component implements drag-and-drop copy and sortable sample code
  • Let's talk again about a series of problems caused by React.js implementing native js drag effects
  • Thoughts on implementing native js drag effects based on React.js
  • React implements simple drag and drop function

<<:  PyTorch development environment installation tutorial under Windows

>>:  Analysis of the project process in idea packaging and uploading to cloud service

Recommend

Media query combined with rem layout in CSS3 to adapt to mobile screens

CSS3 syntax: (1rem = 100px for a 750px design) @m...

JavaScript modularity explained

Table of contents Preface: 1. Concept 2. The bene...

Mysql NULL caused the pit

Using NULL in comparison operators mysql> sele...

How to solve the problem that mysql cannot be closed

Solution to mysql not closing: Right-click on the...

New usage of watch and watchEffect in Vue 3

Table of contents 1. New usage of watch 1.1. Watc...

MySQL 5.7.10 Installation Documentation Tutorial

1. Install dependency packages yum -y install gcc...

MySQL index optimization: paging exploration detailed introduction

Table of contents MySQL Index Optimization Paging...

Docker installs Elasticsearch7.6 cluster and sets password

Starting from Elasticsearch 6.8, free users are a...

Solutions to invalid is Null segment judgment and IFNULL() failure in MySql

MySql Null field judgment and IFNULL failure proc...

A brief discussion on the principle of shallow entry and deep exit of MySQL

Table of contents 1. Overview of the page 2. Infi...

Common structural tags in XHTML

structure body, head, html, title text abbr, acro...

CSS box hide/show and then the top layer implementation code

.imgbox{ width: 1200px; height: 612px; margin-rig...

Some common advanced SQL statements in MySQL

MySQL Advanced SQL Statements use kgc; create tab...