I have a React component App
which is a child of <Router>
. Within App
, I am rendering different Components based on the url path using <Switch>
and <Route>
components.
I know that the role of <Switch>
is to render (only) the first matching <Route>
component.
My App
's render function looks like this.
return (
<Switch>
<Route path='/somepath' component={SomeComponent} />
<Route path='/someotherpath' component={SomeOtherComponent} />
<Main>
<Route path='/anotherpath' component={AnotherComponent} />
<Route component={DefaultComponent} />
</Main>
</Switch>
);
The problem I faced was that when I am rendering AnotherComponent
, DefaultComponent
is also being rendered.
For now, it seems that wrapping the routes in <Main>
into another <Switch>
component will enforce the switch behavior. For example,
<Main>
<Switch>
<Route path='/anotherpath' component={AnotherComponent} />
<Route component={DefaultComponent} />
</Switch>
</Main>
So, is it a good practice to nest <Switch>
components as I did? Is there a more elegant approach to achieve this?