How to combine dynamic and static routes in React

Viewed 157

I need to combine dynamic and static routing in React. In my website i need to display bunch of products and they are displayed by using a dynamic routing <Route path={"/:products"}/> but every single product has his own 'Install' page but by running <Route path ={"/:products/install"}>Install</Route> it doesn't work. In the product page i use link to go to /install route: <Link to="/SF43/install">SF34 install page</Link> How can i solve it?

3 Answers

You are missing exact:

<Route exact path="/:products"/>
<Route exact path ="/:products/install">Install</Route>

Explaining my initial comment.

As stated, you are missing exact in your Route. The exact param comes into play when you have multiple paths that have similar names (your initial problem)

<Route exact path="/:products"/>
<Route exact path ="/:products/install">Install</Route>

What does exact do?

The exact param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.

Where you should define routes?

App.js is a good starting point for main routes. If you have nested components like Parent > Child, and each chuld can be different, then define Parent in App.js and Inside Parent Component, define routes for your Child.

In general, it all depends on your app flow and Architecture

You could try to remove the object in your path prop

Change this

<Route path={"/:products"}/>

for

<Route path="/:products"/>

It's the only thing I saw as a problem here, I've wrote your code just to test and it works

Check it here

Related