Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

86
Views
Mui v5 - TreeView - Collapse all descendants

When I collapse a TreeItem, I want all it's descendants TreeItems (it's children, their children, etc.) that are open to collapse too. At the existing state they do disappear, but the next time I expand the parent TreeItem they are expanded as well.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The TreeView is "uncontrolled" by default meaning that the component will handle the state for you, and you as a consumer get whatever default behavior MUI set. In order to achieve what you want you'll need to make the TreeView a "controlled" component. There is an example of using the controlled component here: https://mui.com/components/tree-view/#controlled-tree-view

The example on the MUI page is doing more than just handling the expanding/collapsing of nodes. In the simplest form you need to explicitly handle the "expanded" prop that gets passed into the TreeView yourself.

const Tree = () => {
  // nodes "1", "1.1", "2" will start expanded
  const [expanded,setExpanded] = useState(["1","1.2","2"]);

  const createHandler = (id) => () => {
    // if node was collapsed, add to expanded list
    if(!expanded.includes(id)) {
      setExpanded([...expanded,id]);
    } else {
      // remove clicked node, and children of clicked node from expanded list
      setExpanded(expanded.filter(i => i !== id && !i.startsWith(`${id}.`));
    }
  };

  return (
    <TreeView expanded={expanded}>
      <TreeItem nodeId="1" label="A" onClick={createHandler("1")}>
        <TreeItem nodeId="1.1" label="B" />
        <TreeItem nodeId="1.2" label="C" onClick={createHandler("1.2")}>
          <TreeItem nodeId="1.2.1" label="D" />
        </TreeItem>
      </TreeItem>
      <TreeItem nodeId="2" label="E" onClick={createHandler("2")}>
        <TreeItem nodeId="2.1" label="F" />
      </TreeItem>
    </TreeView>
  );
}

Note: there be some mistakes in the above example, I'm unable to run it at the moment to verify correctness.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!