Active link color with style using CSS
Setting up... React-Router's Active link Reach-Router's Active link
And one for hookrouter? Here's my effort at start...
function App() {
const routeResult = useRoutes(routes);
const path = usePath();
const activeLink = { color: `${path}` ? "tomato" : "dodgerblue" };
return (
<div>
<div>
<A href="/" style={activeLink}>Home</A>
<A href="/about" style={activeLink}>About</A>
<A href="/contact" style={activeLink}>Contact</A>
</div>
{routeResult || <NotFound />}
</div>
);
}
As the result, whole link show active in tomato color, I was expecting only one active link. Unfortunately, after so many tries and struggles I couldn't come up with solution or have any better idea. I need help What did I do wrong? Any better methods or examples?
The template literal with ${path} will always evaluate to true as long as path.length > 0 - as you can see here hookrouter itself only modifies the onClick handler and href attribute on the anchor element.
You can very easily implement your own wrapper which checks if the current path matches the path of the anchor element.
Example: https://codesandbox.io/s/hookrouter-currentpath-styling-zt6f5