Conditionally set active class on menu using react router current route
For me what worked has is using NavLink
as it has this active class property.
First import it
import { NavLink } from 'react-router-dom';
Use an
activeClassName
to get the active class property.<NavLink to="/" activeClassName="active"> Home </NavLink> <NavLink to="/store" activeClassName="active"> Store </NavLink> <NavLink to="/about" activeClassName="active"> About Us </NavLink>
Style your class in the css by the property
active
..active{ color:#fcfcfc; }
It doesn't look like you're passing the prop into the correct element. The children
of App
would be whatever child route is being rendered (so either Home
or Triangles
), but you want the prop to be passed to Menu
.
To do that, just pass it in via JSX:
import React, {Component} from 'react';
import Menu from './menu';
export default class App extends Component {
render() {
return (
<div>
<Menu location={this.props.location} />
<div className="jumbotron">
{this.props.children}
</div>
</div>
);
}
};
To set class on the active navigation element
import { NavLink } from 'react-router-dom';
&
<NavLink to="/Home" activeClassName="active">Home</NavLink>
You'll want to use React Router's <NavLink>
component that allow you to define styles or add a class when the link is active. Just set the activeClassName
or activeStyle
attribute to your <NavLink>
component.
This is built into React Router, see the official docs for more details: https://reacttraining.com/react-router/web/api/NavLink