It seems none of the solutions presented elsewhere works, so I decided to ask. No matter what I do, I can't get the NavLinks to be rendered differently if they are active or not. I took the ternary operator straight from the part about NavLinks in react-router-dom's documentation and I'd try to create a function to avoid having all this code written three times, but before that I'd like to at least have the correct rendering working.
(side question: why does it break if I remove the Router tags from the return statement? They're there because, before I needed the NavLinks for different styling, I was using regular routes, but if I take them out it breaks with a message about useHref, something like that)
Here's my return statement and the styled-components below it:
return (
<>
<GlobalStyles />
<Router>
<Header />
<Wrapper>
<NavBar>
<NavLink
to="/search"
exact
className={(isActive) =>
"nav-link" + (!isActive ? " inactive" : "")
}>
Search song
</NavLink>
<NavLink
to="/weekly-thread"
exact
className={(isActive) =>
"nav-link" + (!isActive ? " inactive" : "")
}>
Weekly thread
</NavLink>
<NavLink
to="/game"
exact
className={(isActive) =>
"nav-link" + (!isActive ? " inactive" : "")
}>
Game
</NavLink>
</NavBar>
</Wrapper>
</Router>
</>
);
};
const Wrapper = styled.div`
width: 100vw;
height: 100vh;
position: absolute;
z-index: -1;
`;
const NavBar = styled.div`
display: flex;
padding: 20px 20px;
position: relative;
gap: 20px;
font-size: 18px;
a {
text-decoration: none;
}
.nav-link {
color: blue;
&:inactive {
color: black;
}
}
`;
EDIT: it's getting weirder. After even simply pasting the code from the answer below and not getting any results, I tried to mess with the font size for the active NavLink. To my surprise, now something changed, but in totally bizarre way, as it made the first element stay as it were before and second and third got transformed just in terms of font size, but nothing else. When I click on the other NavLinks, the URL changes, but they remain the same: the first in the original size, the other two altered.
SECOND EDIT: Trying to debug this a little further, I've done this to one of my NavLinks and the result is very weird:
<NavLink to="/search" exact className={(isActive) => {
console.log(isActive);
isActive === false ? console.log(isActive) : console.log("foo");
}}>Search song</NavLink>
Now, the first console.log returns the actual value of isActive, but the second and third console.logs always return, "foo", which is the second value in the ternary operator, even if I change "isActive === false" to "isActive === true", which should swap them. I have no idea what is going on here.
After console.logs here, there and everywhere, something struck my attention: isActive appears as an object on the console. That's why I was always getting the same result.
When I changed the condition on the ternary operator to isActive.isActive ?
I started getting the expected results.