I am trying to implement a tree using the material in Reactjs. But, according to my design, the button to collapse and expand should be on the right side.
Also, I am getting an error when added an icon in TreeItem
like this:
<TreeItem nodeId="1" label="RSMSSB" icon={FolderIcon}>
Whole code:
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TreeView from "@material-ui/lab/TreeView";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import TreeItem from "@material-ui/lab/TreeItem";
import FolderIcon from '@material-ui/icons/Folder';
const useStyles = makeStyles({
root: {
height: 216,
flexGrow: 1,
maxWidth: 400
}
});
export default function ControlledTreeView() {
const classes = useStyles();
const [expanded, setExpanded] = React.useState([]);
const handleChange = (event, nodes) => {
setExpanded(nodes);
};
return (
<TreeView
className={classes.root}
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ChevronRightIcon />}
expanded={expanded}
onNodeToggle={handleChange}
>
<TreeItem nodeId="1" label="RSMSSB" icon={FolderIcon}>
<TreeItem nodeId="2" label="Science"></TreeItem>
<TreeItem nodeId="3" label="Mathematics">
<TreeItem nodeId="4" label="Polynomials"></TreeItem>
<TreeItem nodeId="7" label="Inequalities"></TreeItem>
</TreeItem>
<TreeItem nodeId="8" label="English"></TreeItem>
</TreeItem>
</TreeView>
);
}
Mock of design:
Thanks.
EDIT:
working example: https://codesandbox.io/s/purple-night-mgzwh
Based on the Customized tree view example you can create a custom component that takes a text and an icon to pass to the label property of the TreeItem
and to have the expand/collapse icon on the right add flex-direction: row-reverse;
to the content class of the TreeItem
:
const useTreeItemStyles = makeStyles(theme => ({
content: {
flexDirection: 'row-reverse'
},
labelRoot: {
display: 'flex',
alignItems: 'center',
padding: theme.spacing(0.5, 0),
},
labelIcon: {
marginRight: theme.spacing(1),
},
labelText: {
fontWeight: 'inherit',
flexGrow: 1,
},
}));
function StyledTreeItem(props) {
const classes = useTreeItemStyles();
const { labelText, labelIcon: LabelIcon, ...other } = props;
return (
<TreeItem
label={
<div className={classes.labelRoot}>
<LabelIcon color="inherit" className={classes.labelIcon} />
<Typography variant="body2" className={classes.labelText}>
{labelText}
</Typography>
</div>
}
classes={{
content: classes.content
}}
{...other}
/>
);
}
...
<TreeView
className={classes.root}
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ChevronRightIcon />}
expanded={expanded}
onNodeToggle={handleChange}
>
<StyledTreeItem nodeId="1" labelText="RSMSSB" labelIcon={FolderIcon} />
...
Working example:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With