Open In App

ReactJS UI Ant Design TreeSelect Component

Ant Design Library has this component pre-built, and it is very easy to integrate as well. TreeSelect Component is used for the Tree selection control. It is similar to the Select component but here the values are provided in a tree-like structure. We can use the following approach in ReactJS to use the Ant Design TreeSelect Component.

TreeSelect Props:



Tree Methods:

TreeNode Props:



 

Creating React Application And Installing Module:

Project Structure: It will look like the following.

Project Structure

Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.




import React, { useState } from 'react';
import { TreeSelect } from 'antd';
import "antd/dist/antd.css";
  
const { TreeNode } = TreeSelect;
  
export default function App() {
  
  // States to manage current value
  const [value, setValue] = useState(undefined);
  
  return (
    <div style={{
      display: 'block', width: 700, padding: 30
    }}>
      <h4>ReactJS Ant-Design TreeSelect Component</h4>
      <>
        <TreeSelect
          placeholder="Select from the Tree"
          allowClear
          showSearch
          value={value}
          onChange={() => {
            setValue(value);
          }}
        >
          <TreeNode value="Parent" title="Parent">
            <TreeNode value="ChildLeaf1" title="ChildLeaf1" />
            <TreeNode value="ChildLeaf2" title="ChildLeaf2" />
            <TreeNode value="ChildLeaf3" title="ChildLeaf3" />
            <TreeNode value="ChildLeaf4" title="ChildLeaf4" />
            <TreeNode value="ChildLeaf5" title="ChildLeaf5" />
          </TreeNode>
        </TreeSelect>
      </>
    </div>
  );
}

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Reference: https://ant.design/components/tree-select/


Article Tags :