react-component / tree

React Tree
https://tree.react-component.now.sh/
MIT License
1.21k stars 484 forks source link

Open tree on node select #379

Open beqramo opened 4 years ago

beqramo commented 4 years ago

Hi, I want to open tree on node select but I cant find any programmatic or default way to do this and how can I be able to do this?

iloveip commented 4 years ago

I was able to do this with:

const [expandedKeys, setExpandedKeys] = useState([]);
const [selectedKeys, setSelectedKeys] = useState([]);
const [autoExpandParent, setAutoExpandParent] = useState(true);

const onSelect = (selectedKeys, info) => {
  const node = info.node
  if (node.expanded) {
    const id = expandedKeys.indexOf(node.key);
    const newArr = expandedKeys.filter((item, index) => index !== id);
    setExpandedKeys(newArr);
    setAutoExpandParent(false);
  } else {
    setExpandedKeys([...selectedKeys, ...expandedKeys]);
    setAutoExpandParent(false);
  }
};

// In the component
<Tree
  onExpand={onExpand}
  expandedKeys={expandedKeys}
  autoExpandParent={autoExpandParent}
  onSelect={onSelect}
  selectedKeys={selectedKeys}
  treeData={treeData}
/>