How to Drag and Drop using Ant Design in ReactJS

share link

by vsasikalabe dot icon Updated: Mar 28, 2023

technology logo
technology logo

Solution Kit Solution Kit  

Ant Design is a React UI library with too many easy-to-use components that are useful for building simple user interfaces. It's great for building React apps quickly since it has a set of excellent high-quality React components and offers strong support for browsers and server-side rendering. Drag and drop is a process of moving computer files or images from one place to another by clicking on them with the mouse and moving them across the computer screen. 

 

Upload Props: 

  • accept: Used to represent the file types that can be accepted. 
  • data: Used for uploading extra functions, which can return uploading additional criteria. 
  • defaultFileList: Used to represent the Default list of files that have been uploaded. 
  • directory: Used to support uploading the whole directory. 
  • fileList: Used to obtain the list of files or information that has been uploaded. 
  • headers: Used to put request headers. 
  • iconRender: Used to show the icon. 
  • onDrop: It is a callback function operated when files are dragged and dropped into the upload area. 
  • onPreview: It is a callback function activated when a file link or preview icon is clicked. 
  • onRemove: It is a callback function activated when the removing file button is clicked. 

Draggable items are moved using CSS properties. This allows items to be dragged without considering their current state positioning (relative, absolute, or static). Upon sorting, react-sortable-hoc creates a copy of the element you are sorting (the sortable-helper) and adds it to the end of the tag. The original element will still be in place to maintain its position in the DOM until the end of the drag (with inline styling to make it invisible). 

 

Here is an example of how to create drag and drop using ant design in react: 

Preview of the output that you will get on running this code from your IDE

Code:

In this solution we use the React library.

import React from "react";
import "antd/dist/antd.css";
import { Table } from "antd";
import {
  sortableContainer,
  sortableElement,
  sortableHandle
} from "react-sortable-hoc";
import { MenuOutlined } from "@ant-design/icons";

const data = [
  {
    key: "1",
    name: "John Brown",
    age: 32,
    address: "New York No. 1 Lake Park",
    index: 0
  },
  {
    key: "2",
    name: "Jim Green",
    age: 42,
    address: "London No. 1 Lake Park",
    index: 1
  },
  {
    key: "3",
    name: "Joe Black",
    age: 32,
    address: "Sidney No. 1 Lake Park",
    index: 2
  },
  {
    key: "4",
    name: "4",
    age: 32,
    address: "New York No. 1 Lake Park",
    index: 3
  },
  {
    key: "5",
    name: "5",
    age: 42,
    address: "London No. 1 Lake Park",
    index: 4
  },
  {
    key: "6",
    name: "6",
    age: 32,
    address: "Sidney No. 1 Lake Park",
    index: 5
  }
];

const DragHandle = sortableHandle(({ active }) => (
  <MenuOutlined style={{ cursor: "grab", color: active ? "blue" : "#999" }} />
));

const SortableItem = sortableElement((props) => <tr {...props} />);
const SortableContainer = sortableContainer((props) => <tbody {...props} />);

function SortableTable() {
  const [dataSource, setDataSource] = React.useState(data);
  const [selectedItems, setSelectedItems] = React.useState([]);

  const getColumns = () => {
    return [
      {
        title: "Sort",
        dataIndex: "",
        width: 30,
        className: "drag-visible",
        render: (d, dd, i) => (
          <>
            <DragHandle active={selectedItems.includes(i)} />
          </>
        )
      },
      {
        title: "Name",
        dataIndex: "name",
        className: "drag-visible"
      },
      {
        title: "Age",
        dataIndex: "age"
      },
      {
        title: "Address",
        dataIndex: "address"
      }
    ];
  };
  const merge = (a, b, i = 0) => {
    let aa = [...a];
    return [...a.slice(0, i), ...b, ...aa.slice(i, aa.length)];
  };
  const onSortEnd = ({ oldIndex, newIndex }) => {
    let tempDataSource = dataSource;

    if (oldIndex !== newIndex) {
      if (!selectedItems.length) {
        let movingItem = tempDataSource[oldIndex];
        tempDataSource.splice(oldIndex, 1);
        tempDataSource = merge(tempDataSource, [movingItem], newIndex);
      } else {
        let filteredItems = [];
        selectedItems.forEach((d) => {
          filteredItems.push(tempDataSource[d]);
        });
        let newData = [];
        tempDataSource.forEach((d, i) => {
          if (!selectedItems.includes(i)) {
            newData.push(d);
          }
        });
        tempDataSource = [...newData];
        tempDataSource = merge(tempDataSource, filteredItems, newIndex);
      }
      setDataSource(tempDataSource);
      setSelectedItems([]);
    }
  };

  const DraggableContainer = (props) => (
    <SortableContainer
      useDragHandle
      disableAutoscroll
      helperClass="row-dragging"
      onSortEnd={onSortEnd}
      {...props}
    />
  );

  const DraggableBodyRow = ({ className, style, ...restProps }) => {
    // function findIndex base on Table rowKey props and should always be a right array index
    const index = dataSource.findIndex(
      (x) => x.index === restProps["data-row-key"]
    );
    return (
      <SortableItem
        index={index}
        {...restProps}
        selected={selectedItems.length}
        onClick={(e) => {
          if (e.ctrlKey || e.metaKey) {
            selectedItems.includes(index)
              ? selectedItems.splice(selectedItems.indexOf(index), 1)
              : selectedItems.push(index);
            setSelectedItems(selectedItems);
          } else {
            setSelectedItems([]);
          }
        }}
      />
    );
  };

  return (
    <>
      <h3>"CNTRL + Click" to select multiple items</h3>

      <Table
        pagination={false}
        dataSource={dataSource}
        columns={getColumns()}
        rowKey="index"
        components={{
          body: {
            wrapper: DraggableContainer,
            row: DraggableBodyRow
          }
        }}
      />
      {selectedItems.length ? <>{selectedItems.length} items selected </> : ""}
    </>
  );
}

Instructions

Follow the steps carefully to get the output easily.

  1. Install the Node.js and React on your IDE(preferable Visual Studio Code).
  2. Create React Application using npx create-react-app foldername.
  3. cd foldername.
  4. npm i antd.
  5. npm i react-sortable-hoc --force.
  6. npm i @ant-design/icons --force.
  7. Open the folder in IDE.
  8. Copy the code using "copy" button above and paste it into App.js file(remove the earlier code from App.js).
  9. Remove import " antd/dist/antd.css;"
  10. Next add export default SortableTable; to the last line of the code.
  11. Open the terminal from IDE.
  12. npm start to run the file.



You can also refer this url DEMO for getting the above output.

I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.


I found this code snippet by searching for 'Drag and Drop using Ant Design in React' in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in VS Code 1.73.1 version.
  2. The solution is tested on Nodejs 16.14.2 version.
  3. react 18.2.0 version.
  4. react-sortable-hoc 2.0.0 version.
  5. react ant-design/icons 4.8.0 version.
  6. react i antd-5.0.3 version.


Using this solution, we are able to do Drag and Drop using Ant Design in React with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to do Drag and Drop using Ant Design in React.

Dependent Libraries

create-react-appby facebook

JavaScript doticonstar image 100082 doticonVersion:v5.0.1doticon
License: Permissive (MIT)

Set up a modern web app by running one command.

Support
    Quality
      Security
        License
          Reuse

            create-react-appby facebook

            JavaScript doticon star image 100082 doticonVersion:v5.0.1doticon License: Permissive (MIT)

            Set up a modern web app by running one command.
            Support
              Quality
                Security
                  License
                    Reuse

                      You can search for any dependent library on kandi like 'react'.

                      Support

                      1. For any support on kandi solution kits, please use the chat
                      2. For further learning resources, visit the Open Weaver Community learning page

                      See similar Kits and Libraries