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

324
Vistas
How to make a TreeView expanded by default?

By default a @mui TreeView has all its nodes collapsed.

I want it to have all its nodes expanded by default, and I can't find how to do that.

My attempts were to use a method I called handleExpandAll but it doesn't work, the navigator says it renders too many times. Which is weird because without the call it seemingly renders 1 time, but with it it renders an indefinite amount of times.

Maybe one of you guys could help me.

For now my code looks like this :

import { useEffect } from "react";
import classes from "./TreeNavigation.module.css";
import TreeView from "@mui/lab/TreeView";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";
import CustomTreeItem from "../../ui/CustomTreeItem/CustomTreeItem.js";
import { apiStates } from "../Leases/useLeases.js";
import LoadingDiv from "../../ui/LoadingDiv/LoadingDiv.js";

function TreeNavigation(props) {
  const [expanded, setExpanded] = useState([]);
  const [selected, setSelected] = useState([]);

  const handleSelect = (event, nodeId) => {
    props.onItemSelected(nodeId);
  };

  const handleToggle = (event, nodeIds) => {
    setExpanded(nodeIds);
  };

  const handleExpandAll = (length) => {
    setExpanded((oldExpanded) => [...Array(length).keys()]);
  };

  const data = props.data;

  const renderTree = (nodes) => (
    <CustomTreeItem key={nodes.id} nodeId={nodes.id} label={nodes.name}>
      {Array.isArray(nodes.children)
        ? nodes.children.map((node) => renderTree(node))
        : null}
    </CustomTreeItem>
  );

  switch (data.state) {
    case apiStates.ERROR:
      return <p>ERROR: {data.error || "General error"}</p>;
    case apiStates.SUCCESS:
      const batimentsTreeViews = data.data.map((bat) => {
        var b = [];
        for (const key in bat) {
          b = {
            id: key,
            ...bat[key],
          };
        }
        return renderTree(b);
      });

      handleExpandAll(data.data.length);

      return (
        <TreeView
          aria-label="controlled"
          defaultCollapseIcon={<ExpandMoreIcon />}
          defaultExpandIcon={<ChevronRightIcon />}
          expanded={expanded}
          selected={props.selectedId}
          onNodeToggle={handleToggle}
          onNodeSelect={handleSelect}
          sx={{
            flexGrow: 1,
            width: "100%",
            maxWidth: "none",
            overflowY: "auto",
          }}
        >
          {batimentsTreeViews}
        </TreeView>
      );
    default:
      return <LoadingDiv />;
  }
}

export default TreeNavigation;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

did you check with following way?

 const [expanded, setExpanded] = useState([...Array(length).keys()]);

default Mui treeview expands all with this way.

Edit ControlledTreeView Material Demo (forked)

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