Search code examples
antdant-design-pro

Ant Design Transfer Component. Separate functions for the transfer buttons


https://ant.design/components/transfer/

Hey all! I was just wondering is it possible to implement two separate functions on the transfer buttons. For example, I want to run add function when the user clicks transfer to the right and I want to add remove function when the user clicks transfer button to the left.

From the documentation all I could see was both the buttons just trigger onChange function and I dont want that.


Solution

  • The API of Transfer component uses only one function to change the data, but you can call different functions inside onChange depending on the direction:

    import React, { useState } from "react";
    import ReactDOM from "react-dom";
    import "antd/dist/antd.css";
    import "./index.css";
    import { Transfer } from "antd";
    
    const mockData = [];
    for (let i = 0; i < 20; i++) {
      mockData.push({
        key: i.toString(),
        title: `content${i + 1}`,
        description: `description of content${i + 1}`
      });
    }
    
    const initialTargetKeys = mockData
      .filter((item) => +item.key > 10)
      .map((item) => item.key);
    
    const App = () => {
      const [targetKeys, setTargetKeys] = useState(initialTargetKeys);
      const [selectedKeys, setSelectedKeys] = useState([]);
    
      const handleAdd = (nextTargetKeys, moveKeys) => {
        console.log("add");
        setTargetKeys(nextTargetKeys);
      };
      const handleDelete = (nextTargetKeys, moveKeys) => {
        console.log("delete");
        setTargetKeys(nextTargetKeys);
      };
    
      const onChange = (nextTargetKeys, direction, moveKeys) => {
        if (direction === "left") {
          handleDelete(nextTargetKeys, moveKeys);
        } else {
          handleAdd(nextTargetKeys, moveKeys);
        }
      };
    
      const onSelectChange = (sourceSelectedKeys, targetSelectedKeys) => {
        setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
      };
    
      return (
        <Transfer
          dataSource={mockData}
          titles={["Source", "Target"]}
          targetKeys={targetKeys}
          selectedKeys={selectedKeys}
          onChange={onChange}
          onSelectChange={onSelectChange}
          render={(item) => item.title}
        />
      );
    };
    
    ReactDOM.render(<App />, document.getElementById("container"));