How to add nested routes with React Router v4 or v5?

Sometimes, we want to add nested routes with React Router v4 or v5.

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

How to add nested routes with React Router v4 or v5?

To add nested routes with React Router v4 or v5, we can nest Route components in the render prop function.

For instance, we write

<BrowserRouter>
  <Route path="/" component={Frontpage} exact />
  <Route path="/home" component={HomePage} />
  <Route path="/about" component={AboutPage} />

  <Route
    path="/admin"
    render={({ match: { url } }) => (
      <>
        <Route path={`${url}/`} component={Test} exact />
        <Route path={`${url}/home`} component={Dashboard} />
        <Route path={`${url}/users`} component={UserPage} />
      </>
    )}
  />
</BrowserRouter>;

to set the render prop to render a fragment with multiple nested Route components.

We set the path to the url with the path append to the url after that.

Also, we set the path prop of the Router with the render prop to set the root url for the nested routes.

Conclusion

To add nested routes with React Router v4 or v5, we can nest Route components in the render prop function.