In a React project, I have created menu which has some links as seen in the image below, I have also changed background color of link and color of text when active, but, I want to change icon image i.e it would replace the icon image when active. So what could be the appropriate solution?
Below is the code for your reference:
<List>
{itemList.map((item, index) => {
return (
<ListItem
button
key={item.text}
onClick={() => {
setData(item.text);
}}
>
<NavLink
exact
to={item.link}
style={{ display: "flex", flexWrap: "wrap" }}
activeStyle={{ backgroundColor: "purple", color: "white" }}
>
{item.icon && (
<img
src={item.icon}
style={{ marginRight: "25px" }}
height="18px"
/>
)}
<ListItemText primary={item.text} />
</NavLink>
</ListItem>
);
})}
</List>
I have tried with following code:
const [newActiveLink, setNewActiveLink] = useState(false)
<NavLink
exact
to={item.link}
style={{ display: "flex", flexWrap: "wrap" }}
activeStyle={{ backgroundColor: "purple", color: "white" }}
isActive={(match, location) => match ? setNewActiveLink(true) : setNewActiveLink(false)}
>
...
{
newActiveLink == true ? {item.icon && (
<img
src={item.iconWhite}
style={{ marginRight: "25px" }}
height="18px"
/>
)} : {item.icon && (
<img
src={item.icon}
style={{ marginRight: "25px" }}
height="18px"
/>
)}
}
</NavLink>
But background color disappears when isActive is used
Find this codesandbox link: https://codesandbox.io/s/react-material-forked-3uuyg
