How to add nested routes in React Router v4?

Sometimes, we want to add nested routes in React Router v4.

In this article, we’ll look at how to add nested routes in React Router v4.

How to add nested routes in React Router v4?

To add nested routes in React Router v4, we can nest Route components in a Switch component.

For instance, we write

<div>
  <Route component={AppShell} />
  <Switch>
    <Route exact path="/" component={Login} />
    <Route path="/dashboard" component={Dashboard} />
    <Route component={NoMatch} />
  </Switch>
</div>

to put some Routes side the Switch component and put one Route above the Switch component.

Now they can all coexist without errors.

Conclusion

To add nested routes in React Router v4, we can nest Route components in a Switch component.