Categories
React Answers

How to add nested routes in React Router v4?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *