Reputation: 304
Is there a way to know when the NavLink
is active? something like this?:
<NavLink to="/mylink" activeClassName="active" onActive={this.doSomething} />
Upvotes: 3
Views: 2896
Reputation: 5748
You can use NavLink
's isActive
callback to achieve this. isActive
lets you define your own behaviour when the link is active; it gets the match
and your current location
object. You can modify it to take a callback that will fire if match is true. Here is a simple example:
const isActive = onActive => (match, location) => {
if (match) {
onActive();
}
return match;
}
const App = () => {
const onActive = () => console.log("link is active");
return (
<BrowserRouter>
<div>
<NavLink to="/abc" activeClassName="active" isActive={isActive(onActive)}>Go To ABC</NavLink>
<Route path="/abc" render={() => <h1>ABC Page</h1>} />
</div>
</BrowserRouter>
);
}
Upvotes: 5