Animated sortable list visualization with React logos and a maine coon cat

Unleash Sortable Magic with react-sortable-hoc in React

The Orange Cat
The Orange Cat

React applications often require interactive lists that users can reorder through drag-and-drop interactions. The react-sortable-hoc library provides an elegant solution to this common requirement, offering a set of higher-order components (HOCs) that can transform any list into a sortable, touch-friendly, and animated component.

Features

react-sortable-hoc comes packed with a variety of features that make it a versatile choice for implementing sortable lists:

  • Higher-Order Components: Easily integrate with your existing components
  • Drag Handles: Customize which part of an item can be used to initiate dragging
  • Auto-scrolling: Automatically scroll the container when dragging near edges
  • Axis Locking: Restrict movement to vertical, horizontal, or both
  • Animation: Smooth transitions for a polished user experience
  • Touch Support: Works seamlessly on mobile devices
  • Accessibility: Supports keyboard-based sorting for improved usability

Installation

To get started with react-sortable-hoc, you can install it using npm or yarn:

npm install react-sortable-hoc --save

or

yarn add react-sortable-hoc

Basic Usage

Let’s dive into a basic example to demonstrate how to create a sortable list using react-sortable-hoc.

Creating a Sortable List

First, we’ll import the necessary components and functions:

import React, { useState } from 'react';
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
import { arrayMoveImmutable } from 'array-move';

Next, we’ll define our sortable item and list components:

const SortableItem = SortableElement(({ value }: { value: string }) => (
  <li>{value}</li>
));

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

Now, let’s create our main component that uses these sortable components:

const SortableComponent: React.FC = () => {
  const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5']);

  const onSortEnd = ({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) => {
    setItems(arrayMoveImmutable(items, oldIndex, newIndex));
  };

  return <SortableList items={items} onSortEnd={onSortEnd} />;
};

This basic example creates a sortable list where items can be dragged and reordered. The onSortEnd function updates the state with the new order of items using the arrayMoveImmutable function from the array-move package.

Advanced Usage

Now that we’ve covered the basics, let’s explore some more advanced features of react-sortable-hoc.

Custom Drag Handles

Sometimes, you may want to restrict where users can click to drag an item. You can achieve this using the SortableHandle HOC:

const DragHandle = SortableHandle(() => <span>::</span>);

const SortableItem = SortableElement(({ value }: { value: string }) => (
  <li>
    <DragHandle />
    {value}
  </li>
));

Axis Locking

To restrict movement to a single axis, you can use the axis prop:

<SortableList items={items} onSortEnd={onSortEnd} axis="y" />

This will limit sorting to the vertical axis only.

Auto-scrolling

Enable auto-scrolling when dragging items near the edge of the container:

<SortableList
  items={items}
  onSortEnd={onSortEnd}
  useWindowAsScrollContainer
/>

Customizing Animation

You can customize the animation of items as they’re being sorted:

const SortableList = SortableContainer(({ items }: { items: string[] }) => {
  return (
    <ul>
      {items.map((value, index) => (
        <SortableItem
          key={`item-${value}`}
          index={index}
          value={value}
          style={{
            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
          }}
        />
      ))}
    </ul>
  );
});

Conclusion

react-sortable-hoc provides a powerful and flexible way to add sorting functionality to your React applications. With its wide range of features and easy integration, you can quickly create interactive, touch-friendly, and accessible sortable lists. Whether you’re building a simple todo list or a complex drag-and-drop interface, react-sortable-hoc offers the tools you need to create engaging user experiences.

Remember to explore the library’s documentation for more advanced features and customization options. Happy sorting!

Comments