Reputation: 144
Function to check if, when I click on button on Navbar, go to the page and add a class 'Active' on it.
checkToActive(to) {
return (to === this.props.location.pathname) ? 'Active' : '';
}
My button
<Button state={this.checkToActive("/listening")} text="Listening" to="/listening" />
So.. when I click and go to the page /listening the button get 'Active' class, but when I go to /listening/subPage the button don't have it.. what can I do to make this work?
Thanks.
Upvotes: 0
Views: 33
Reputation: 825
Try this:
checkToActive(to) {
return this.props.location.pathname.includes(to) ? 'Active' : '';
}
Upvotes: 0
Reputation: 196
Change your code like this:
checkToActive(to) {
return (this.props.location.pathname.contains(to)) ? 'Active' : '';
}
Upvotes: 0
Reputation: 825
In react-router
v4 you can use <NavLink>
if you want to do conditional styling or applying class when route matches.
It has already been answered here: https://stackoverflow.com/a/63135768/8996532
Upvotes: 1