i am using with v5 MUI, and How to cancel the collapse event of the first item?
Like ALL in the picture
and remove dropdown icon
like list item in the picture
To my knowledge, there's no way to disable the expand/collapse functionality of an individual TreeItem
in uncontrolled mode (if that's what you're running). Presumably, you should be able to easily change your TreeView
to run in controlled mode, by keeping the expanded item list in state, passing that list to the TreeView
's expanded
prop, and then force it to keep top-level items expanded by not providing a click handler for the TreeItem
(s) that you don't want to collapse. For example:
...
// Setting the top-level node's nodeId to "expanded", by default
const [expanded, setExpanded] = React.useState(["1"]);
// Handle the expand logic however you choose (this is just an example)
const createHandler = (id) => () => {
if (!expanded.includes(id)) {
setExpanded([...expanded, id]);
} else {
setExpanded(
expanded.filter((i) => {
return i !== id && !i.startsWith(`${id}.`);
})
);
}
};
...
return (
<TreeView
className={classes.root}
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ChevronRightIcon />}
expanded={expanded}
>
{/* Don't provide a click handler to this node so it won't collapse */}
{/* Note: I'm passing an empty fragment to the `collapseIcon` prop so no collapse icon is displayed */}
<TreeItem nodeId="1" label="All Items" collapseIcon={<></>}>
{/* Provide a click handler for all collapsible children */}
<TreeItem
nodeId="2"
label="Second Level Item"
onClick={createHandler("2")}
/>
...
</TreeView>
);
...
The example above also includes a method for removing the collapse icon by passing an empty React Fragment to the collapseIcon
prop -- But you could also achieve this with some clever CSS, if you prefer.
Working CodeSandbox: https://codesandbox.io/s/material-demo-forked-4nmsp6?file=/demo.tsx:1514-1699