Reputation: 375
I have this react app where the structure is EnglishRoute -> Mainpage -> Treatments -> TreatmentItem
In the EnglishRoute, I have:
<p>english route</p>
<Switch>
<Route path=`en` exact>
<MainPage />
</Route>
<Route path=`en/quote`>
<NewQuote />
</Route>
<Route path=`en/rendering`>
<Regions />
</Route>
</Switch>
In my TreatmentItem.js I have:
<li>
<Link to=`en/rendering`>Rendering React</Link>
</li>
</ul>
<Switch>
<Route path=`en/rendering`>
<Regions />
</Route>
</Switch>
I want to be able to render the component <Regions>
from TreatmentItem.js but it does
not work. But when have the same <Route path=`en/rendering`>
inside EnglishRoute
, it
gets the same <Regions />
component rendered and everything loads fine...
<Link to=`en/rendering`>
correctly put the url.
I feel like I am forgetting something really silly, what can I do to fix this issue?
Upvotes: 1
Views: 257
Reputation: 202618
Inside the Switch
component route path order and specificity matters. In this case you've added the exact
prop to the Route
rendering MainPage
on path"/en"
. When you click the link and navigate to "/en/rendering"
the path no longer exactly matches "/en"
and the MainPage
component is unmounted.
This is why the path="en/rendering"
route works when it's outside on it's own with the Switch
but not when it's rendered by MainPage
/../TreatmentItem
.
The route path order and specificity matters inside the Switch
. If ordered correctly there is almost zero need to use the exact
prop. Reorder the routes in the inverse order of path specificity, i.e. the more specific routes should be listed before the less specific routes. Remove the exact
prop.
Example:
<Switch>
<Route path="en/quote" component={NewQuote} />
<Route path="en" component={MainPage} />
</Switch>
Now when the path is "/en/rendering"
it won't match "/en/quote"
and route matching will continue down and be matched by "/en"
and render the MainPage
component. Since MainPage
is rendering TreatmentItem
and another Switch
with a Route
on "/en/rendering"
this path is also matched and the Regions
component is rendered.
Upvotes: 2