I have tried multiple solutions found elsewhere without success, so I am reaching out for help. I am struggling to render NavLinks differently based on whether they are active or not. I followed the ternary operator logic from the react-router-dom documentation for NavLinks but cannot get it to work as expected. Initially, I considered creating a function to avoid repeating code three times, but first, I need to resolve the rendering issue.
(side question: why does removing the Router tags from the return statement cause a break? Initially, I used regular routes before styling the NavLinks differently and had to add Router tags. Without them, I encounter an error related to useHref)
Below is my return statement along with the styled-components:
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: The situation has become even stranger. After pasting the provided code solution and seeing no changes, I attempted to adjust the font size for the active NavLink. Surprisingly, only the second and third elements were affected while the first one remained unchanged in terms of appearance. When clicking on other NavLinks, the URL updates but their styles stay inconsistent.
SECOND EDIT: Trying to troubleshoot further, I added console logs to one of the NavLinks:
<NavLink to="/search" exact className={(isActive) => {
console.log(isActive);
isActive === false ? console.log(isActive) : console.log("foo");
}}>Search song</NavLink>
The first console log correctly shows the value of isActive, but the subsequent ones always display "foo," regardless of the condition. Even swapping "isActive === false" to "isActive === true" does not change this unexpected behavior. This issue is perplexing me.