React Router v4 Active NavLink Route

I am trying to migrate my project using v3 react-router to v4 of what is now called react-router-dom . Now problems arise when I have a MenuBar component that is completely separate from the routing logic (as you would expect), as it will show the same links no matter what the current path is. Now this works well with v3, but now when I use NavLink , which has the same activeClassName property, the active route is not updated on the NavBar, only when updated. It seems a little silly, so there should be a way around this.

 export default @inject('ui') @observer class App extends Component { render() { return ( <Router> <div className={ styles.wrapper }> <Sidebar /> <main className={ `${styles.main} ${!this.props.ui.menuOpen && styles.closed}` }> <Route exact path="/" component={ HomePage } /> <Route path="/signup" component={ SignUpPage } /> <Route path="/login" component={ LoginPage } /> <Route path="/about" component={ AboutPage } /> </main> <footer className="site-footer"></footer> </div> </Router> ); } } 

This is my main application logic, and since you can see that the routes are nested, but the router itself wraps around the entire component.

What should I add to make them work again? (They work correctly when refreshing the page)

+6
source share
1 answer

Based on the use of the @observer decorator, it seems like you are using mobx-react . What you need to know about observer is that it implements shouldComponentUpdate to optimize rendering performance. This sCU call will look at the current and next details, and if there is no difference, it will not be re-rendered. This is a problem because, by default, the React Router uses context to transfer data and uses re-rendering of elements to get updated values, but observer sCU not able to detect context changes.

The way you can get around this is to pass the location object as a support for the component wrapped by the observer . Then, when the location changes, observer shouldComponentUpdate detect the difference and re-render.

You can see the blocked upgrade guide for more information.

+4
source

Source: https://habr.com/ru/post/1015690/


All Articles