Ask Your Question
4

How can I choose only the parent in a tree using React and Ant Design instead of selecting the child as well?

asked 2023-07-07 20:09:07 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-07 20:27:02 +0000

scrum gravatar image

You can create a function to handle the selection of the parent node in the tree. In this function, you can set the state to only select the parent node by checking if the clicked node has any children. If the clicked node is a parent node, you can set the state to select it and deselect any previously selected child node. Here is an example code snippet:

import { Tree } from 'antd';

const { TreeNode } = Tree;

class MyTree extends React.Component {
  state = {
    selectedKeys: [],
  };

  onSelect = (selectedKeys, { selected, node }) => {
    if (!node.children) {
      // Current node is a leaf node, do nothing
      return;
    }

    if (selected) {
      // Node is selected, update the state
      this.setState({ selectedKeys: [node.key] });
    } else {
      // Node is deselected
      this.setState({ selectedKeys: [] });
    }
  };

  render() {
    return (
      <Tree
        selectedKeys={this.state.selectedKeys}
        onSelect={this.onSelect}
      >
        <TreeNode key="parent" title="Parent Node">
          <TreeNode key="child1" title="Child Node 1" />
          <TreeNode key="child2" title="Child Node 2" />
        </TreeNode>
      </Tree>
    );
  }
}

In the onSelect function, we check if the clicked node has any children by checking the node.children property. If it doesn't have any children, we do nothing and the selectedKeys state is not updated. If the clicked node is a parent node, we update the state to only select that node and deselect any previously selected child node by setting selectedKeys to an array with only the parent node key. If the node is deselected, we simply set selectedKeys to an empty array.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-07 20:09:07 +0000

Seen: 12 times

Last updated: Jul 07 '23