Search code examples
javascriptreactjsnestedreact-routerreact-router-v4

Nested routes with react router v4 / v5


I am currently struggling with nesting routes using react router v4.

The closest example was the route config in the React-Router v4 Documentation.

I want to split my app in 2 different parts.

A frontend and an admin area.

I was thinking about something like this:

<Match pattern="/" component={Frontpage}>
  <Match pattern="/home" component={HomePage} />
  <Match pattern="/about" component={AboutPage} />
</Match>
<Match pattern="/admin" component={Backend}>
  <Match pattern="/home" component={Dashboard} />
  <Match pattern="/users" component={UserPage} />
</Match>
<Miss component={NotFoundPage} />

The frontend has a different layout and style than the admin area. So within the frontpage the route home, about and so one should be the child routes.

/home should be rendered into the Frontpage component and /admin/home should be rendered within the Backend component.

I tried some other variations but I always ended in not hitting /home or /admin/home.


Solution

  • In react-router-v4 you don't nest <Routes />. Instead, you put them inside another <Component />.


    For instance

    <Route path='/topics' component={Topics}>
      <Route path='/topics/:topicId' component={Topic} />
    </Route>
    

    should become

    <Route path='/topics' component={Topics} />
    

    with

    const Topics = ({ match }) => (
      <div>
        <h2>Topics</h2>
        <Link to={`${match.url}/exampleTopicId`}>
          Example topic
        </Link>
        <Route path={`${match.path}/:topicId`} component={Topic}/>
      </div>
    ) 
    

    Here is a basic example straight from the react-router documentation.