Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

95
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda