skip to Main Content

I’ve been working with react-router-rom v6 for a little while now and was experimenting with nested routes. I had experience doing this in v5 without problem. I have followed some tutorials and looked up examples how to properly do nested routes in v6, but can’t seem to understand what I may be missing.

Below is a portion of the nested route. When I navigate to "/users", it renders the Users component without issue. When I navigate to the "/users/invite" it still only ever renders the Users component.

<Routes>
  <Route path='users' element={<Users />}>
    <Route path='invite' element={<Invite />} />
  </Route>
</Routes>

From what I understand, navigating to "/users" should render the Users component and navigating to "/users/invite" should render the Invite component since it’s nested inside of the <Route/> component.

2

Answers


  1. The component is where the child route component will be rendered, so you need to include it in your parent route component. For example, in your Users component, you need to do like this:

    function Users() {
      return (
        <div>
          <h1>Users</h1>
          <Link to="invite">Invite a user</Link>
          <Outlet />
        </div>
      );
    }
    
    Login or Signup to reply.
  2. If you want Users and Invite to be matched and rendered independently then one can’t be nested within the other. Render them as sibling routes.

    Example:

    <Routes>
      <Route path="/users" element={<Users />} />
      <Route path="/users/invite" element={<Invite />} />
    </Routes>
    

    or

    <Routes>
      <Route path='/users'>
        <Route index element={<Users />} />
        <Route path="invite" element={<Invite />} />
      </Route>
    </Routes>
    

    If you do actually want Users to be rendered as part of a layout when the path is "/users/invite" then Users necessarily should render an Outlet component for nested routes to render their element content into.

    Example:

    import { Outlet } from 'react-router-dom';
    
    const Users = () => {
      ...
    
      return (
        ...
    
        <Outlet /> // <-- nested route content rendered here
        ...
      );
    };
    
    <Routes>
      <Route path="/users" element={<Users />}>
        <Route path="invite" element={<Invite />} />
      </Route>
    </Routes>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search