Henrique Mota
Henrique Mota

Reputation: 144

Check if page has on link to add class on it

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

Answers (3)

Yogendra Chauhan
Yogendra Chauhan

Reputation: 825

Try this:

checkToActive(to) {
    return this.props.location.pathname.includes(to) ? 'Active' : '';
}

Upvotes: 0

bthn
bthn

Reputation: 196

Change your code like this:

 checkToActive(to) {
           return (this.props.location.pathname.contains(to)) ? 'Active' : '';
    }

Upvotes: 0

Yogendra Chauhan
Yogendra Chauhan

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

Related Questions