Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

92
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda