React Router – URL Changes, Component Doesn’t

React logo

There’s nothing more frustrating when something just doesn’t work. And coding is no exception.

You’re searching high and low, your Link component is fine, and you’ve been through your code a million times.

The address bar in your browser updates to your new URL, the your component doesn’t change – and stubbornly remains glued to the screen.

This a common case for many React developers who have a potentially troublesome combination of:

  • Using Redux connect
  • Not using a route component – i.e. component={ReactComponent}

Fortunately though, there’s an easy fix.

In Enters, withRouter

Given the conditions above, Redux and React Router often don’t play nicely together. I won’t bore you with the detail here (as I realise at this stage you’ve probably already tore half your hair out!) but just trust me on this one.

The solution however is simple. We need to treat all of our non-route component with corresponding export connects.

  1. Extend your import statement for react-router-dom to include ‘withRouter’.

Code before:

import { Route, Link } from 'react-router-dom';

Code after:

import { Route, Link, withRouter } from 'react-router-dom';
  1. Surround your export with ‘withRouter’.

Code before:

export default connect(mapStateToProps)(AppDisplay);

Code after:

export default withRouter(connect(mapStateToProps)(AppDisplay));

Rinse and repeat for all connected components and voilá, your app routes correctly, your components load and your zen is restored.

Shout out to us in the comments section below if we’ve just saved your sanity! You’re welcome!!

You may also like...

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x