I have a footer with 5 links, which I am using a Mui Button for with component={Link} to transform into links.
The buttons are all black, I have a hover state that changes the button to green when hovered over, but I want to keep the button color green if it has been clicked.
At the moment the onClick is changing all the buttons to green not just the active one.
I have tried several different solutions-all result in same issue. Thank you so much to anyone that can help!
solution fail #1:
const styles = {
footerLogo: {
width: '300px',
height: '57px',
align: 'center'
},
navLink: {
fontSize: '16px',
color: 'black',
"&:hover":{
color:'green'
}
},
active: {
color: 'green'
}
};
const navButtons = [
{
button: "Services",
link: "/services",
},
{
button: "Featured Work",
link: "/work",
},
{
button: "About",
link: "/about",
},
{
button: "Contact",
link: "/contact",
},
];
const location = window.location.pathname;
const currentTab = location === navButtons[0].link ? styles.active : styles.navLink
<Box
display='flex'
justifyContent='space-around'
marginTop='50px'
>
{navButtons.map(({button, link, index}) => (
<Button
key={index}
to={link}
component={Link}
sx={currentTab}
>
{button}
</Button>
))}
</Box>
solution fail #2:
const [isClicked, setIsClicked] = useState(false);
const handleClick = () => {
setIsClicked(true)
}
<Box
display='flex'
justifyContent='space-around'
marginTop='50px'
>
{navButtons.map(({button, link, index}) => (
<Button
key={index}
to={link}
component={Link}
onClick={handleClick}
sx={{
color : isClicked ? "green" : "black",
":hover":{
color:'green'
}
}}
>
{button}
</Button>
))}
</Box>
2
Answers
In first solution, you are always comparing location with first navbutton link i.e navButtons[0].link
As for you second solution
isClicked state is for the component and not for individual button. So rather than having one state for isClicked you can keep isClicked in your navBtn array.