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.
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.