Education
Software Development Executive - I
Last updated on Jun 4, 2024
Last updated on Oct 20, 2023
Have you ever found yourself struggling to arrange a list of items in your React application? Whether you're building a to-do list, a gallery, or a playlist, the need for a sortable list is quite common. Here React Sortable HOC plays a significant role. It's a set of higher-order components that can be leveraged to create sortable elements in your React applications.
React Sortable HOC, or Higher-Order Component, is a technique in React for reusing component logic. Simply put, a higher-order component is a function that takes a component and returns a new component. React Sortable HOC, in particular, is a set of React higher-order components intended to provide sortable functionality to your components with minimal fuss. It's a wrapper component that encapsulates the drag-and-drop functionality, allowing you to turn any component into a sortable element.
Before diving into the intricacies of React Sortable HOC, it's crucial to set up your React project correctly. This involves importing necessary modules, setting up a development environment, and creating your first sortable component.
To begin with, you need to import React and ArrayMove into your project. ArrayMove is a simple utility function that will help us manipulate arrays, which is essential when dealing with sortable lists. Here's how you can import these modules:
1import React from 'react'; 2import arrayMove from 'array-move';
React Storybook is a user interface development environment and playground for UI components. It allows you to create components independently and showcase components interactively in an isolated development environment. To launch React Storybook, you can use the following command in your terminal:
1npm run storybook
Creating a sortable component with React Sortable HOC involves wrapping your existing component with the sortableElement HOC. This HOC adds the necessary props to make your component sortable. Here's a basic example of how to create a sortable list item:
1import { sortableElement } from 'react-sortable-hoc'; 2 3const SortableItem = sortableElement(({value}) => <li>{value}</li>);
In this example, SortableItem is a new component that you can use just like any other React component, but it has sortable functionality thanks to the sortableElement HOC.
One of the core features of React Sortable HOC is its ability to implement drag-and-drop functionality.
The sortable helper in React Sortable HOC is a cloned sortable element that follows the cursor when dragging. It's the element that users see moving around the screen when they drag an item. The sortable helper can be customized to fit your needs, but by default, it's a clone of the element being sorted.
In React Sortable HOC, you can specify which part of your component should be used as the drag handle. This is the part of the component that users will click and drag to move the component. By default, the entire component is used as the drag handle, but you can customize this by wrapping the desired part of your component with the sortableHandle HOC.
1import { sortableHandle } from 'react-sortable-hoc'; 2 3const DragHandle = sortableHandle(() => <span>::</span>); 4 5const SortableItem = sortableElement(({value}) => ( 6 <li> 7 <DragHandle /> 8 {value} 9 </li> 10));
In this example, the :: span is the drag handle. Users can click and drag this span to move the list item.
To add sortable functionality to an existing component, you need to wrap it with the sortableElement HOC, as shown in the previous section. But to create a sortable list, you also need to wrap your list component with the sortableContainer HOC. This HOC adds the necessary props and methods to your list component to manage the sortable items.
1import { sortableContainer } from 'react-sortable-hoc'; 2 3const SortableList = sortableContainer(({children}) => { 4 return <ul>{children}</ul>; 5}); 6 7// Usage 8<SortableList> 9 {items.map((value, index) => ( 10 <SortableItem key={`item-${value}`} index={index} value={value} /> 11 ))} 12</SortableList>
In this example, SortableList is a new component that renders an unordered list. You can use this component to render your SortableItem components, and they will have sortable functionality.
React Sortable HOC comes packed with a wealth of features that make it a powerful tool for enhancing the user interface of your web applications. In this section, we'll explore some of these features, including variable width support, grid support, scrollable container elements, and more.
React Sortable HOC supports elements with variable widths and heights, making it a versatile tool for creating sortable lists. This means you can have a list where each item has a different size, and React Sortable HOC will handle it gracefully.
In addition to variable width support, React Sortable HOC also offers grid support. This means you can create sortable lists that are arranged in a grid, rather than just a single column or row. This is particularly useful for creating drag-and-drop interfaces that resemble a desktop or a dashboard.
React Sortable HOC allows you to specify a scrollable container element. This is useful when your sortable list is inside a container with overflow: auto or overflow: scroll, and you want the container to automatically scroll when you drag an item to the edge of the container.
In addition, React Sortable HOC gives you access to the outermost HTML node rendered by the sortable element. This can be useful for a variety of purposes, such as applying styles or attaching event listeners.
React Sortable HOC allows you to provide a custom container object. This can be useful if you want to customize the container that wraps your sortable elements.
Furthermore, as mentioned earlier, React Sortable HOC uses a cloned sortable helper by default. This is the element that follows the cursor when dragging. However, you can customize this by providing a custom sortable helper. This can be useful if you want the helper to look different from the sortable element, or if you want to optimize performance by using a simpler, lighter-weight helper.
React Sortable HOC provides a variety of callbacks and properties that you can use to customize the behavior of your sortable components. Understanding these callbacks and properties is essential to make the most out of React Sortable HOC.
React Sortable HOC provides several callbacks that you can use to respond to different events in the lifecycle of a sortable element. Here's a brief overview of these callbacks:
Here's an example of how to use these callbacks:
1<SortableList 2 onSortEnd={({oldIndex, newIndex}) => { 3 setItems(arrayMove(items, oldIndex, newIndex)); 4 }} 5 onSortStart={({node, index}) => console.log("Sorting started")} 6 onSortMove={() => console.log("Sortable element moved")} 7 onSortOver={() => console.log("Sortable element moved over another element")} 8/>
React Sortable HOC provides several properties that you can use to customize the behavior of your sortable components. Here's a brief overview of these properties:
Here's an example of how to use these properties:
1<SortableItem 2 disabled={false} 3 useDragHandle={true} 4 lockToContainerEdges={true} 5/>
React Sortable HOC supports keyboard sorting out of the box. This means that users can sort elements using their keyboard, which can be a great accessibility feature. You can customize the keycodes used for keyboard sorting by providing an array of keycodes.
For example, you might want to use the arrow keys for sorting. Here's how you can do that:
1<SortableList 2 shouldUseDragHandle={true} 3 helperClass="sortableHelper" 4 onSortEnd={this.onSortEnd} 5 pressDelay={200} 6 axis="xy" 7/>
In this example, the shouldUseDragHandle property is set to true, which means that sorting can only be initiated by dragging the drag handle. The helperClass property is used to apply a custom CSS class to the sortable helper. The onSortEnd callback is used to update the state of the component when sorting ends. The pressDelay property is used to delay the onset of sorting, and the axis property is used to specify the direction of sorting.
As you delve deeper into React Sortable HOC, you'll encounter some advanced concepts that can further enhance your sortable lists. This section will explore working with multiple groups, disabling transitions, and understanding the concept of higher-order components and the wrapped component.
React Sortable HOC allows you to create multiple groups of sortable elements. Each group can be sorted independently, and elements cannot be dragged from one group to another. This can be useful for creating complex interfaces with multiple independent sortable lists.
In addition, React Sortable HOC gives you access to the DOM element of each sortable element. This can be useful for a variety of purposes, such as applying styles or attaching event listeners.
Here's an example of how to create multiple groups and access the DOM element:
1const SortableItem = sortableElement(({value}) => { 2 const ref = React.useRef(null); 3 4 React.useEffect(() => { 5 // You can access the DOM element here 6 const domElement = ref.current; 7 }, []); 8 9 return <li ref={ref}>{value}</li>; 10}); 11 12const SortableList1 = sortableContainer(({items}) => ( 13 <ul> 14 {items.map((value, index) => ( 15 <SortableItem key={`item-${value}`} index={index} value={value} /> 16 ))} 17 </ul> 18)); 19 20const SortableList2 = sortableContainer(({items}) => ( 21 <ul> 22 {items.map((value, index) => ( 23 <SortableItem key={`item-${value}`} index={index} value={value} /> 24 ))} 25 </ul> 26));
In this example, SortableList1 and SortableList2 are two independent groups of sortable elements.
In some cases, you might want to disable transitions in your sortable list. For example, you might want to disable transitions while dragging to improve performance. React Sortable HOC provides a transitionDuration property that you can use to disable transitions:
1<SortableList transitionDuration={0} />
In this example, setting transitionDuration to 0 disables transitions.
As mentioned earlier, React Sortable HOC is a set of higher-order components (HOCs). An HOC is a function that takes a component and returns a new component with additional props and/or behavior. In the case of React Sortable HOC, the HOCs add sortable functionality to the wrapped component.
The wrapped component is the component that you pass to the HOC. This is the component that will become sortable. The wrapped component will receive a number of additional props from the HOC, such as index, isDragging, and isSorting.
Here's an example of a wrapped component:
1const MyComponent = ({isDragging, isSorting}) => ( 2 <div style={{opacity: isDragging ? 0.5 : 1}}> 3 I am a sortable component! 4 </div> 5); 6 7const SortableComponent = sortableElement(MyComponent);
In this example, MyComponent is the wrapped component, and SortableComponent is the new component returned by the sortableElement HOC. SortableComponent has the same interface as MyComponent, but it also has sortable functionality.
React Sortable HOC is a powerful tool for creating sortable lists in your React applications. Its flexibility and customization options make it a versatile tool that can cater to a wide range of use cases. From setting up your React project, implementing drag and drop functionality, exploring the various features, and understanding callbacks and properties, to delving into advanced concepts like working with multiple groups and higher-order components, we've covered a lot of ground.
However, the true power of React Sortable HOC lies in its ability to be tailored to your specific needs. Whether you're building a simple to-do list or a complex dashboard with multiple independent sortable lists, React Sortable HOC has got you covered. With its intuitive drag-and-drop interface and customizable options, you can easily create interactive and user-friendly sortable lists.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.
Tired coding all day?
Do it with a few clicks.