0

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?

Jun Park
  • 508
  • 1
  • 6
  • 20
  • @iamcaleberic it is perfectly fine to have unconditional Route in a Switch. It is the fallback in case none of the previous Route matched. – Pierre Kraemer Jan 29 '18 at 12:53
  • 1
    @jun-park `Switch` only manages its direct `Route` (or `Redirect`) children. You can refer to this question that exposes the same problem as yours: https://stackoverflow.com/questions/43830068/react-router-v4-nested-routes-with-switch. Considering your question about good practices, I guess there is no problem with nested `Switch`. – Pierre Kraemer Jan 29 '18 at 12:56
  • @iamcaleberic in these examples from the docs, the fallback Route of the Switch does not have a defined path prop: https://reacttraining.com/react-router/web/api/Switch, https://reacttraining.com/react-router/web/example/no-match – Pierre Kraemer Jan 29 '18 at 13:34
  • @PierreKraemer seen that thanks for the correction – iamcaleberic Jan 29 '18 at 13:59

0 Answers0