I have some links in a nav menu that outputs html something like this:
<ul>
<li>
<a href="/">Home</a>
</li>
<li>
<a href="/subs">Subs</a>
</li>
</ul>
I'm trying to add a class only to the current page link in the nav menu (e.g. if you're on the / page then the home link should have a class added to it) as per the solution of this post, however, I'm getting the following error:
TypeError: Cannot read property 'route' of undefined
Here is the component:
import React, {Component} from "react";
import {Link} from "react-router-dom";
import {navLinks} from "../util/nav-links";
export default class NavMenu extends React.Component {
render() {
var isActive = this.context.router.route.location.pathname === this.props.to;
var className = isActive ? 'active' : '';
const lis = navLinks.map(link => (
<li>
<Link className={className} to={link.href} key={link.href}>{link.name}</Link>
</li>
)
)
return (
<div id="navbar">
<ul>
{lis}
</ul>
</div>
)
}
}
And the /util/nav-links.js file:
export const navLinks = [
{
name: "home",
href: "/"
},
{
name: "subs",
href: "/subs"
}
];
Why is this error occuring? If the two variables isActive
and className
and the className
in the link tag are removed then the code works. Also, if there's a better way of achieving this then does anyone have any other methods?
Thanks for any help here. Stackblitz demo: https://stackblitz.com/edit/react-jhedf8?file=src%2Fcomponents%2Fnav-menu.js