How to change the colors of icons when the active state of the button is changed? I’m using SVG icons since they are convenient. How can I modify the SideBarButton
component to conditionally apply styles to the icon based on the active state. How can I achieve this ? Here are the SideBarButton and SideBar component codes (briefly)
const SideNavbar = ({ onSideNavBarClick }) => {
const [activeButton, setActiveButton] = useState("Dashboard");
const handleClick = (page) => {
setActiveButton(page);
onSideNavBarClick(page);
};
return (
<SidebarWrapper>
<SidebarBody>
<UnorderedList>
{makeButtons.map((btn, i) => (
<SideBarButton
key={i}
onClick={() => handleClick(btn.title)}
icon={btn.icon}
title={btn.title}
isActive={btn.title === activeButton}
/>
))}
</UnorderedList>
</SidebarBody>
</SidebarWrapper>
);
};
const makeButtons = [
{ icon: <img src={dashboard} alt="dashboard" />, title: "Dashboard" },
{ icon: <img src={patient} alt="patient" />, title: "Patients" },
{ icon: <img src={visits} alt="visits" />, title: "Appointments" },
{ icon: <img src={appointments} alt="appointments" />, title: "Visits" },
];
const SideBarButton = ({ onClick, icon, title, isActive }) => {
return (
<li>
<ButtonSidebar onClick={onClick} className={isActive ? "active" : ""}>
<Icon>{icon}</Icon>
{title}
</ButtonSidebar>
</li>
);
};
2
Answers
A simple is create a array of button like this
You can use
NavLink
fromreact-router-dom
which will help in routing and will provide a check for the active state as well:Separate Icon for active and inactive state (replace with your icons):