Convert Figma logo to code with AI

SortableJS logoreact-sortablejs

React bindings for SortableJS

2,025
209
2,025
103

Top Related Projects

A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable list✌️

Beautiful and accessible drag and drop for lists with React

Drag-and-drop sortable component for nested data and hierarchies

20,879

Drag and Drop for React

🖱 A resizable and draggable component for React.

A draggable and resizable grid layout with responsive breakpoints, for React.

Quick Overview

React-SortableJS is a React wrapper for the SortableJS library, providing drag-and-drop functionality for lists and grids in React applications. It allows developers to create sortable interfaces with minimal configuration while leveraging the power of React components.

Pros

  • Easy integration with React projects
  • Highly customizable with various options and callbacks
  • Supports both vertical and horizontal sorting
  • Works well with touch devices and modern browsers

Cons

  • Limited documentation compared to the core SortableJS library
  • May have performance issues with large lists or complex nested structures
  • Occasional conflicts with other React libraries or state management solutions
  • Learning curve for advanced usage and customization

Code Examples

  1. Basic sortable list:
import { ReactSortable } from "react-sortablejs";

function SortableList() {
  const [list, setList] = useState([
    { id: 1, name: "Item 1" },
    { id: 2, name: "Item 2" },
    { id: 3, name: "Item 3" },
  ]);

  return (
    <ReactSortable list={list} setList={setList}>
      {list.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </ReactSortable>
  );
}
  1. Nested sortable lists:
import { ReactSortable } from "react-sortablejs";

function NestedSortable({ items, setItems }) {
  return (
    <ReactSortable list={items} setList={setItems}>
      {items.map((item) => (
        <div key={item.id}>
          {item.name}
          {item.children && (
            <NestedSortable items={item.children} setItems={(newChildren) => {
              const newItems = [...items];
              const index = newItems.findIndex((i) => i.id === item.id);
              newItems[index].children = newChildren;
              setItems(newItems);
            }} />
          )}
        </div>
      ))}
    </ReactSortable>
  );
}
  1. Sortable with custom handle:
import { ReactSortable } from "react-sortablejs";

function SortableWithHandle() {
  const [list, setList] = useState([
    { id: 1, name: "Item 1" },
    { id: 2, name: "Item 2" },
    { id: 3, name: "Item 3" },
  ]);

  return (
    <ReactSortable list={list} setList={setList} handle=".handle">
      {list.map((item) => (
        <div key={item.id}>
          <span className="handle"></span> {item.name}
        </div>
      ))}
    </ReactSortable>
  );
}

Getting Started

  1. Install the package:

    npm install react-sortablejs sortablejs
    
  2. Import and use in your React component:

    import { ReactSortable } from "react-sortablejs";
    
    function MyComponent() {
      const [list, setList] = useState([
        { id: 1, name: "Item 1" },
        { id: 2, name: "Item 2" },
      ]);
    
      return (
        <ReactSortable list={list} setList={setList}>
          {list.map((item) => (
            <div key={item.id}>{item.name}</div>
          ))}
        </ReactSortable>
      );
    }
    
  3. Customize as needed using the available props and options from the SortableJS library.

Competitor Comparisons

A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable list✌️

Pros of react-sortable-hoc

  • More flexible and customizable, allowing for complex sorting scenarios
  • Better performance for large lists due to virtualization support
  • Stronger TypeScript support and type definitions

Cons of react-sortable-hoc

  • Steeper learning curve due to its higher complexity
  • Less intuitive API compared to react-sortablejs
  • Requires more boilerplate code for basic implementations

Code Comparison

react-sortable-hoc:

import { SortableContainer, SortableElement } from 'react-sortable-hoc';

const SortableItem = SortableElement(({value}) => <li>{value}</li>);
const SortableList = SortableContainer(({items}) => {
  return (
    <ul>
      {items.map((value, index) => (
        <SortableItem key={`item-${index}`} index={index} value={value} />
      ))}
    </ul>
  );
});

react-sortablejs:

import { ReactSortable } from "react-sortablejs";

function App() {
  const [state, setState] = useState([{ id: 1, name: "Item 1" }]);
  return (
    <ReactSortable list={state} setList={setState}>
      {state.map((item) => <div key={item.id}>{item.name}</div>)}
    </ReactSortable>
  );
}

Both libraries offer drag-and-drop functionality for React applications, but react-sortable-hoc provides more advanced features at the cost of complexity, while react-sortablejs offers a simpler API for basic sorting needs.

Beautiful and accessible drag and drop for lists with React

Pros of react-beautiful-dnd

  • More accessible out of the box, with built-in keyboard support
  • Smoother animations and visual feedback during drag operations
  • Extensive documentation and examples provided by Atlassian

Cons of react-beautiful-dnd

  • Limited to vertical lists and horizontal lists; no support for grids or multi-dimensional sorting
  • Larger bundle size compared to react-sortablejs
  • Less flexible for customization of drag behavior

Code Comparison

react-beautiful-dnd:

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

<DragDropContext onDragEnd={onDragEnd}>
  <Droppable droppableId="list">
    {(provided) => (
      <ul {...provided.droppableProps} ref={provided.innerRef}>
        {items.map((item, index) => (
          <Draggable key={item.id} draggableId={item.id} index={index}>
            {(provided) => (
              <li ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps}>
                {item.content}
              </li>
            )}
          </Draggable>
        ))}
        {provided.placeholder}
      </ul>
    )}
  </Droppable>
</DragDropContext>

react-sortablejs:

import { ReactSortable } from "react-sortablejs";

<ReactSortable list={items} setList={setItems}>
  {items.map((item) => (
    <div key={item.id}>{item.content}</div>
  ))}
</ReactSortable>

Drag-and-drop sortable component for nested data and hierarchies

Pros of react-sortable-tree

  • Specifically designed for tree structures, making it ideal for hierarchical data
  • Includes built-in node adding, removing, and searching functionality
  • Supports custom node rendering and styling out of the box

Cons of react-sortable-tree

  • Limited to tree structures, less flexible for other types of sortable layouts
  • Steeper learning curve due to its specialized nature
  • Less active development and community support compared to react-sortablejs

Code Comparison

react-sortable-tree:

<SortableTree
  treeData={this.state.treeData}
  onChange={treeData => this.setState({ treeData })}
  generateNodeProps={({ node, path }) => ({
    title: node.title,
  })}
/>

react-sortablejs:

<ReactSortable list={this.state.list} setList={newState => this.setState({list: newState})}>
  {this.state.list.map(item => (
    <div key={item.id}>{item.name}</div>
  ))}
</ReactSortable>

The code comparison shows that react-sortable-tree is more focused on tree structures with built-in node properties, while react-sortablejs offers a more generic sortable list implementation. react-sortablejs provides greater flexibility for various sorting scenarios, whereas react-sortable-tree excels in handling hierarchical data with its specialized features.

20,879

Drag and Drop for React

Pros of react-dnd

  • More flexible and customizable for complex drag-and-drop scenarios
  • Better integration with React's component model and state management
  • Supports touch devices and keyboard accessibility out of the box

Cons of react-dnd

  • Steeper learning curve and more boilerplate code required
  • Less performant for large lists or grids of draggable items
  • Requires more setup and configuration for basic use cases

Code Comparison

react-dnd:

import { useDrag, useDrop } from 'react-dnd';

function DraggableItem({ id, text }) {
  const [{ isDragging }, drag] = useDrag(() => ({
    type: 'ITEM',
    item: { id },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  }));

  return <div ref={drag}>{text}</div>;
}

react-sortablejs:

import { ReactSortable } from "react-sortablejs";

function SortableList({ items, setItems }) {
  return (
    <ReactSortable list={items} setList={setItems}>
      {items.map((item) => <div key={item.id}>{item.text}</div>)}
    </ReactSortable>
  );
}

The code comparison shows that react-sortablejs requires less setup for basic sorting functionality, while react-dnd offers more granular control over the drag-and-drop behavior at the cost of additional complexity.

🖱 A resizable and draggable component for React.

Pros of react-rnd

  • Offers both resizing and dragging functionality, providing more versatile component manipulation
  • Supports custom handles for resizing, allowing for greater UI customization
  • Provides more fine-grained control over component positioning and dimensions

Cons of react-rnd

  • Less focused on sorting and reordering, which is the primary function of react-sortablejs
  • May have a steeper learning curve due to its additional features and configuration options
  • Potentially heavier in terms of bundle size due to its broader feature set

Code Comparison

react-rnd:

<Rnd
  default={{
    x: 0, y: 0,
    width: 320, height: 200
  }}
>
  Resizable and Draggable Component
</Rnd>

react-sortablejs:

<ReactSortable list={items} setList={setItems}>
  {items.map(item => (
    <div key={item.id}>{item.name}</div>
  ))}
</ReactSortable>

The code examples highlight the different focus of each library. react-rnd emphasizes positioning and resizing, while react-sortablejs concentrates on list management and sorting functionality.

A draggable and resizable grid layout with responsive breakpoints, for React.

Pros of react-grid-layout

  • Specifically designed for grid layouts, offering more advanced grid functionality
  • Supports responsive breakpoints for different screen sizes
  • Provides built-in resizing capabilities for grid items

Cons of react-grid-layout

  • Steeper learning curve due to more complex API
  • Less flexible for non-grid layouts or simple drag-and-drop scenarios
  • Heavier bundle size compared to react-sortablejs

Code Comparison

react-grid-layout:

import GridLayout from 'react-grid-layout';

<GridLayout
  className="layout"
  layout={layout}
  cols={12}
  rowHeight={30}
  width={1200}
>
  {children}
</GridLayout>

react-sortablejs:

import { ReactSortable } from "react-sortablejs";

<ReactSortable list={items} setList={setItems}>
  {items.map((item) => (
    <div key={item.id}>{item.name}</div>
  ))}
</ReactSortable>

react-grid-layout is more suitable for complex grid-based layouts with resizing capabilities, while react-sortablejs excels in simpler drag-and-drop scenarios with a more straightforward API. Choose based on your specific layout requirements and desired level of customization.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

react-sortablejs

React bindings to SortableJS

semantic-release

Please note that this is not considered ready for production, as there are still a number of bugs being sent through.

Features

Installation

sortablejs and @types/sortablejs are peer dependencies. The latter is only used if intellisense/typescript is desired.

npm install --save react-sortablejs sortablejs
npm install --save-dev @types/sortablejs

# OR
yarn add react-sortablejs sortablejs
yarn add -D @types/sortablejs

Learn

Here is the TLDR of what sortable is:

- Shopping List: # list of items / sortable. This represents `react-sortablejs`
  - eggs # list item. These are all the items in the list and are what you move around.
  - bread # list item
  - milk # list item

Usage/Examples

Function Component

import React, { FC, useState } from "react";
import { ReactSortable } from "react-sortablejs";

interface ItemType {
  id: number;
  name: string;
}

export const BasicFunction: FC = (props) => {
  const [state, setState] = useState<ItemType[]>([
    { id: 1, name: "shrek" },
    { id: 2, name: "fiona" },
  ]);

  return (
    <ReactSortable list={state} setList={setState}>
      {state.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </ReactSortable>
  );
};

Class Component

import React, { Component } from "react";
import { ReactSortable } from "react-sortablejs";

interface BasicClassState {
  list: { id: string; name: string }[];
}

export class BasicClass extends Component<{}, BasicClassState> {
  state: BasicClassState = {
    list: [{ id: "1", name: "shrek" }],
  };
  render() {
    return (
      <ReactSortable
        list={this.state.list}
        setList={(newState) => this.setState({ list: newState })}
      >
        {this.state.list.map((item) => (
          <div key={item.id}>{item.name}</div>
        ))}
      </ReactSortable>
    );
  }
}

Plugins

Sortable has some pretty cool plugins such as MultiDrag and Swap.

By Default:

  • AutoScroll is premounted and enabled.
  • OnSpill is premounted and NOT enabled.
  • MultiDrag and Swap and NOT premounted and NOT enabled

You must mount the plugin with sortable ONCE ONLY.

import React from "react";
import { ReactSortable, Sortable, MultiDrag, Swap } from "react-sortablejs";

// mount whatever plugins you'd like to. These are the only current options.
Sortable.mount(new MultiDrag(), new Swap());

const App = () => {
  const [state, setState] = useState([
    { id: 1, name: "shrek" },
    { id: 2, name: "fiona" },
  ]);

  return (
    <ReactSortable
      multiDrag // enables mutidrag
      // OR
      swap // enables swap
    >
      {state.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </ReactSortable>
  );
};

Sortable API

For a comprehensive list of options, please visit https://github.com/SortableJS/Sortable#options.

Those options are applied as follows.

Sortable.create(element, {
  group: " groupName",
  animation: 200,
  delayOnTouchStart: true,
  delay: 2,
});

// --------------------------
// Will now be...
// --------------------------

import React from "react";
import { ReactSortable } from "react-sortablejs";

const App = () => {
  const [state, setState] = useState([
    { id: 1, name: "shrek" },
    { id: 2, name: "fiona" },
  ]);

  return (
    <ReactSortable
      // here they are!
      group="groupName"
      animation={200}
      delayOnTouchStart={true}
      delay={2}
    >
      {state.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </ReactSortable>
  );
};

React API

id, className, style

These are all default DOM attributes. Nothing special here.

list

The same as state in const [ state, setState] = useState([{ id: 1}, {id: 2}])

state must be an array of items, with each item being an object that has the following shape:

  /** The unique id associated with your item. It's recommended this is the same as the key prop for your list item. */
  id: string | number;
  /** When true, the item is selected using MultiDrag */
  selected?: boolean;
  /** When true, the item is deemed "chosen", which basically just a mousedown event. */
  chosen?: boolean;
  /** When true, it will not be possible to pick this item up in the list. */
  filtered?: boolean;
  [property: string]: any;

setList

The same as setState in const [ state, setState] = useState([{ id: 1}, {id: 2}])

clone

If you're using {group: { name: 'groupName', pull: 'clone'}}, this means you're in 'clone' mode. You should provide a function for this.

Check out the source code of the clone example for more information. I'll write it here soon.

tag

ReactSortable is a div element by default. This can be changed to be any HTML element (for example ul, ol) or can be a React component.

This value, be it the component or the HTML element, should be passed down under props.tag.

Let's explore both here.

HTML Element

Here we will use an ul. You can use any HTML. Just add the string and ReactSortable will use a ul instead of a div.

import React, { FC, useState } from "react";
import { ReactSortable } from "react-sortablejs";

export const BasicFunction: FC = (props) => {
  const [state, setState] = useState([{ id: "1", name: "shrek" }]);

  return (
    <ReactSortable tag="ul" list={state} setList={setState}>
      {state.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ReactSortable>
  );
};

Custom Component

When using a custom component in the tag prop, the only component it allows is a forwardRef component. Currently, we only support components that use the React.forwardRef API.

If it doesn't have one, you can add one using React.forwardRef().

todo: Some third-party UI components may have nested elements to create the look they're after. This could be an issue and not sure how to fix it.

import React, { FC, useState, forwardRef } from "react";
import { ReactSortable } from "react-sortablejs";

// This is just like a normal component, but now has a ref.
const CustomComponent = forwardRef<HTMLDivElement, any>((props, ref) => {
  return <div ref={ref}>{props.children}</div>;
});

export const BasicFunction: FC = (props) => {
  const [state, setState] = useState([
    { id: 1, name: "shrek" },
    { id: 2, name: "fiona" },
  ]);

  return (
    <ReactSortable tag={CustomComponent} list={state} setList={setState}>
      {state.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </ReactSortable>
  );
};

How does it work?

Sortable affects the DOM, adding, and removing nodes/css when it needs to in order to achieve the smooth transitions we all know an love. This component reverses many of its actions of the DOM so React can handle this when the state changes.

Caveats / Gotchas

key !== index

DO NOT use the index as a key for your list items. Sorting will not work.

In all the examples above, I used an object with an ID. You should do the same!

I may even enforce this into the design to eliminate errors.

Nesting

Problem

Basically, the child updates the state twice. I'm working on this.

What does work?

Our usage indicates that as long as we only move items between lists that don't use the same setState function.

I hope to provide an example soon.

Solutions

We don't have anything that works 100%, but here I'd like to spitball some potential avenues to look down.

  • Use onMove to handle state changes instead of onAdd,onRemove, etc.
  • Create a Sortable plugin specifically for react-sortbalejs

NPM DownloadsLast 30 Days