I have an array of objects which bassically are sidebar items. Every object has a MUI 5 icon. In a sidebar component I render it in a map function. I'd like to have a selected item to be highlighted...I managed to change the font color but don't know how to change icon color.
So the question is how to change icon color in Sidebar.tsx?
routes.tsx
export const SIDEBAR_PATHS = [
{
id: 1,
path: PATHS.projects,
name: 'Projects',
icon: <AccountTreeIcon />,
},
{
id: 2,
path: PATHS.faces,
name: 'Faces',
icon: <FaceRetouchingNaturalIcon />,
},
];
Sidebart.tsx
{SIDEBAR_PATHS.map(({ id, path, name, icon }) => (
<ListItem key={id} disablePadding>
<ListItemButton disableRipple onClick={() => navigate(path)} selected={path === pathname}>
{icon}
<ListItemText primary={name} primaryTypographyProps={{ fontWeight: 500 }} />
</ListItemButton>
</ListItem>
))}
CodePudding user response:
but don't know how to change icon color.
I'd change your icon
field from JSX
type (already called react component) to FC
(a react component) so you can call it later and pass props into it.
Then, just tweak the color of the icon depending on the selected
prop.
export const SIDEBAR_PATHS = [
{
id: 1,
path: PATHS.projects,
name: 'Projects',
icon: AccountTreeIcon
},
{
id: 2,
path: PATHS.faces,
name: 'Faces',
icon: FaceRetouchingNaturalIcon,
},
];
{SIDEBAR_PATHS.map(({ id, path, name, icon }) => {
const Icon = icon;
return (
<ListItem key={id} disablePadding>
<ListItemButton disableRipple onClick={() => navigate(path)} selected={path === pathname}>
<Icon style={{ color: selected ? 'green' : 'red'} />
// ^^^^^^^^^^^^^^^^ toggle the color of icon
<ListItemText primary={name} primaryTypographyProps={{ fontWeight: 500 }} />
</ListItemButton>
</ListItem>
);
})}
CodePudding user response:
For mui 5 you could try this. Mui provides SvgIcon component for the same purpose.
import { SvgIcon } from "@mui/material";
....
{SIDEBAR_PATHS.map(({ id, path, name, icon }) => {
return (
<ListItem key={id} disablePadding>
<ListItemButton disableRipple onClick={() => navigate(path)} selected={path === pathname}>
<SvgIcon style={{ color: path === pathname ? 'green' : 'blue' }}{icon}</SvgIcon>
<ListItemText primary={name} primaryTypographyProps={{ fontWeight: 500 }} />
</ListItemButton>
</ListItem>
);
})}