dgreene1 / react-accessible-treeview

A react component that implements the treeview pattern as described by the WAI-ARIA Authoring Practices.
https://dgreene1.github.io/react-accessible-treeview
MIT License
277 stars 37 forks source link

How can I access "treeState" out of nodeRenderer function as a globally? #151

Closed yashrabari closed 1 year ago

dgreene1 commented 1 year ago

Please take this question to stack overflow since it’s a general react question.

mt-deva commented 8 months ago

I'll leave an example for others to learn from @yashrabari

function FileTree({ data }) {
  // tree state in global
  const [currentTreeState, setCurrentTreeState] = useState<ITreeViewState>();

  // useCallback so we dont create a new anon function for every item
  const handleUpdate = useCallback((treeState) => {
    setCurrentTreeState(treeState);
  }, []);

  return (
    <TreeView
        data={data}
        nodeRenderer={({ element, treeState }) => {    
        // update state on every click
        return (<button onClick={() => handleUpdate(treeState)>{element.name}</span>);
        }}
     />

    // the state is now available in the outer component
        <Button onClick={() => console.log(currentTreeState)}>Log Current Tree State</Button>
    </div>
</div>
  );
}