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;
did you check with following way?
const [expanded, setExpanded] = useState([...Array(length).keys()]);
default Mui treeview expands all with this way.