React Router Frequently Faced Problems

Shoaib Bhimani
3 min readApr 22, 2018

--

React Router Frequently Faced Problems

Routing is one of the trickiest things to implement in a Single Page App using React. In the React ecosystem, it’s pretty much an industry standard to use React Router for routing. React Router has a nice API and is pleasant to work with, but there are a few issues that I’ve faced while using it.

Problem #1: Component Not Rendering

If you have declared a component and it’s not rendering, there could be three possible issues:

  1. If you are using any state management solutions like Redux or Mobx, and you have assigned different components to render in different paths using the render function instead of the component property, both will essentially do the same thing.

When clicking the index (“/”) route link, you will see the URL change to “/about”, but the corresponding component does not get rendered. The reason is that Redux/Mobx only look for changes in state and props, not changes in the URL. To overcome this, you can use withRouter from React Router, which injects the history as props to the component. Now, since history is added to this component, whenever the URL or history changes, the component will re-render, and you will see the correct output.

Solution for Problem #1: Wrap the component with withRouter to get the history prop and ensure it re-renders on URL changes.

Solution for Problem #1 Mentioned above

2. The exact property is often used to make sure a component renders only for exactly matched routes. However, there is a hidden meaning to it. If you have nested components, they won't render when using exact, and surprisingly, React Router doesn't throw any error.

Example:

Be carefull when using Exact in React Router

In this example, the “/test” and “/test1” routes in the Home component will never render because we added exact while declaring the Home component. To fix this, remove exact from its parent component.

Problem #3: Recommended Approach for Adding Nested Routes

Instead of hard-coding paths in the Path property, it is recommended to use the match prop passed by React Router to the component.

Using match.url will take care of the nested URL, and you only need to add the trailing path specific to this route.

Example Sandbox: CodeSandbox Link

If you found this post helpful, please click the 👏 button below to show your support!

--

--