Trying to learn React through coding, I've encountered an issue with displaying the 'StarBorder' icon next to folders when clicked. Currently, clicking on any folder displays the 'StarBorder' icon for all folders. Any tips on how to ensure that it only appears on the folder that is clicked? The icon should appear only when 'console.log("check state", toggleSiteCheckmark)' returns true. If a selected folder is clicked again, the 'StarBorder' should hide as a toggle.
You can test it out here: https://codesandbox.io/s/nestedlist-demo-material-ui-forked-pul8sk?file=/demo.tsx:0-2556
Below is the code snippet:
import React, { useEffect, useRef, useState } from "react";
import ListSubheader from "@mui/material/ListSubheader";
import List from "@mui/material/List";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import Collapse from "@mui/material/Collapse";
import InboxIcon from "@mui/icons-material/MoveToInbox";
import ExpandLess from "@mui/icons-material/ExpandLess";
import ExpandMore from "@mui/icons-material/ExpandMore";
import StarBorder from "@mui/icons-material/StarBorder";
export default function NestedList() {
const [open, setOpen] = useState(true);
const [toggleSiteCheckmark, setToggleSiteCheckmark] = useState(false);
const handleClick = () => {
setOpen(!open);
};
const handleSelected = () => {
setToggleSiteCheckmark(!toggleSiteCheckmark);
};
console.log("check state", toggleSiteCheckmark);
return (
<List
sx={{ width: "100%", maxWidth: 360, bgcolor: "background.paper" }}
component="nav"
aria-labelledby="nested-list-subheader"
subheader={
<ListSubheader component="div" id="nested-list-subheader">
Nested List Items
</ListSubheader>
}
>
<ListItemButton onClick={handleClick}>
<ListItemIcon>
<InboxIcon />
</ListItemIcon>
<ListItemText primary="Folder" />
{open ? <ExpandLess /> : <ExpandMore />}
</ListItemButton>
<Collapse in={open} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
<ListItemButton onClick={handleSelected} sx={{ pl: 4 }}>
<ListItemIcon>{toggleSiteCheckmark && <StarBorder />}</ListItemIcon>
<ListItemText primary="Inbox" />
</ListItemButton>
<ListItemButton onClick={handleSelected} sx={{ pl: 4 }}>
<ListItemIcon>{toggleSiteCheckmark && <StarBorder />}</ListItemIcon>
<ListItemText primary="Sent Items" />
</ListItemButton>
<ListItemButton onClick={handleSelected} sx={{ pl: 4 }}>
<ListItemIcon>{toggleSiteCheckmark && <StarBorder />}</ListItemIcon>
<ListItemText primary="Deleted Items" />
</ListItemButton>
<ListItemButton onClick={handleSelected} sx={{ pl: 4 }}>
<ListItemIcon>{toggleSiteCheckmark && <StarBorder />}</ListItemIcon>
<ListItemText primary="Archieve" />
</ListItemButton>
</List>
</Collapse>
</List>
);
}
English is not my native language, so there may be errors.