react-smooth-draggable

The React framework provides two dimensional sorting functionality that is missing from various drag and drop sorting libraries.

Specific effects can be viewed by clicking the video

For single-column or single-row sorting, react-smooth-dnd is recommended.

Getting Started

npm install react-smooth-draggable -S
Copy the code

In a component that uses react-smooth-draggable,

import React, { useState } from 'react';
import Draggable from 'react-smooth-draggable';
import styles from './index.less';

export default function Index() {
  const [list, setList] = useState(() = >
    Array(16).fill(0).map((_, index) = > ({ id: index + 1})));const onDragEnd = ({ list, /* dragIndex, dropIndex */ }) = > setList(list);

  return (
    <Draggable
      list={list}
      onDragEnd={onDragEnd}
      cols={4}
      height={80}
      dragClass={styles.dragClass}
      itemClass={styles.itemClass}
      wraperClass={styles.wraperClass}
    >
      {item => <span>{item.id}</span>}
    </Draggable>
  );
}
Copy the code

At the end of the drag, you must call the onDragEnd method to update the state of the list

props

Name Type Default Description
list {Array} [] When sorting an array of lists, make sure that each entry has a unique ID attribute that is used as a key
onDragStart {Function} undefined Method to execute when the drag begins, taking the currently dragged index dragIndex
onDragEnd {Function} {list, dragIndex, dropIndex}, list isAfter orderingThe list of
cols {Number} 1 It appears as several columns
height {Number} 80 The height of a single element, in px, must be fixed
render {Function} undefined Customize the rendering method for each item with the current item data object
children {Function|ReactElement|null} null Same as render, preferentially use render when render exists
dragClass {String} ‘ ‘ The style class name of the item that moves with the mouse when dragging
itemClass {String} ‘ ‘ The style class name of the normal item
wraperClass {String} ‘ ‘ The name of the style class that directly wraps the rendering portion of each item

The relationship between dragClass, itemClass, and wraperClass is only a pseudo-code example

<div className={styles.DragContainer}>
    <div className={itemClass}>
        <div className={wraperClass}>{ render(item1) }</div>
    </div>
    <div className={itemClass}>
        <div className={wraperClass}>{ render(item2) }</div>
    </div>
    {/* when dragging item3 */}
    <div className={classnames(itemClass, dragClass)}>
        <div className={wraperClass}>{ render(item3) }</div>
    </div>
    ...
</div>
Copy the code

License

MIT

Keywords

react, sortable, drag and drop, drag&drop, drag, drop, draggable, dnd, smooth