Visit The School

React-router: If Your Links Aren't Appearing Active

Alexander Paterson
|
Posted about 1 year ago
|
2 minutes
React-router: If Your Links Aren't Appearing Active
I had a problem with activeClassName that took a while to fix

This is just a small tip regarding react-router: if your Links are in a component other than a component listed in your router, then their activeClassName property won't work properly. The active class will be assigned when you initially load the page, but clicking links won't change the active link. 

For example, if you have a router that looks like this:

ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory}>
      <Route path="/" component={Main}>
        <IndexRoute component={Home}/>
        <Route path="login" component={Login}/>
        <Route path="signup" component={Signup}/>
      </Route>
    </Router>
  </Provider>,
  document.getElementById('app')
);

And your Main component has a render method that looks like this, where a Navbar component is rendered:

return (
  <div>
    <Navbar/>
    <div style={{minHeight: "70vh"}}>
      {this.props.children}
    </div>
  </div>
);

Then any Links in the Navbar component won't be assigned active classes properly.

The solution for me was to merge my Navbar code into my Main component.

<div>
  <div className="top-bar">
    <div key={1} className="menu-item">
      <div>
        <Link to="login" activeClassName="active-link">Log In</Link>
      </div>
    </div>
    <div key={2} className="menu-item">
      <div>
        <Link to="signup" activeClassName="active-link">Sign Up</Link>
      </div>
    </div>
  </div>
  <div style={{minHeight: "70vh"}}>
    {this.props.children}
  </div>
</div>

React-router provides a function called withRouter which wraps around components to provide access to the router as a prop, but wrapping Navbar with it didn't fix the problem for me.

Hope this saves you some time.



ALEXANDER
PATERSON