iannbing / react-simple-tree-menu

A simple React tree menu component
MIT License
137 stars 48 forks source link

On Click listener for expand/collapse button #205

Closed impsinha closed 1 year ago

impsinha commented 2 years ago

Problem - Basically I want to control expand/collapse from both UI and outside UI. On setting openNodes params, I am able to expand/collapse from outside UI but I am not able to expand/collapse through UI.

Possible solution - If we have 'on click listener' for expand/collapse button, we will be able to maintain the state of openNodes params through useState and we will be able to set the openNodes state from 'on click listener' and outside as well.

Another possible solution would be to use useEffect to enforce the re-rendering the component from outside by using initialOpenNodes params but I am losing the previous openNodes state in that case.

In case, there is any workaround to achieve this in current version, please enlighten me.

iannbing commented 1 year ago

@impsinha If it still matters, you can use resetOpenNodes to achieve this. See the following example:


    const treeMenuRef = useRef()

    <>
      <button
        style={{ margin: '4px' }}
        onClick={() =>
          treeMenuRef.current.resetOpenNodes(
            ['mammal', 'mammal/canidae'],
            'mammal/canidae'
          )
        }
      >
        Open/Highlight Canidae
      </button>

      <TreeMenu
        data={dataInArray}
        onClickItem={action(`on click node`)}
        ref={treeMenuRef}
      />
    </>