2

I have 3 routes that use the same component and based on the route display slightly different content. The problem is that on every route change the whole components mounts/unmounts from scratch leading to performance issues. What is the best way to avoid the unmounting but still use the same component and have these 3 routes?

<Route path="/Products" exact render={Products} />
<Route path="/Products/shoes" exact component={Products} />
<Route path="/Products/books" exact component={Products} />

React Router version 4.

3
  • which version of react-router you are using Commented Jun 5, 2018 at 10:24
  • @stack26 version 4 Commented Jun 5, 2018 at 10:28
  • Can you try <Route path="/Products/:type?" exact render={Products} /> and see if it mounts/unmounts each time ? Commented Jun 5, 2018 at 10:35

3 Answers 3

3

You can render Route based on route conditional path matching, in which case it wont remount everytime your route changes

<Route path="/Products(/shoes|/books)?" exact render={Products} />
Sign up to request clarification or add additional context in comments.

Comments

0

Shubham's solution is now a little different, here two years later

<Route path={["/Products/shoes", "/Products/books", "/Products"]} exact render={Products} />

Notice the order.

Comments

-1

The routes in parallel will unmount whenever a new route is matched. you need to wrap the component for "/Products/shoes" and "/Products/books" inside Product component. In react-router v4, You need to nest the routes similar to your component. so you need to have product component containing the "/Products" route and other 2 inside the child component.

Frankly speaking I just gave an overview, read through react-router 4 documentation for better understanding.

1 Comment

That’s not correct. You don’t have to nest. @Shubham is right on replacing component prop by render.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.