1

As expected, when navigating to direct children such as Develop, the component rendered is <Develop />.

When navigating to sub-children such as Web, the route changes to /develop/web as expected, however, the component that's rendered is of the parent <Develop />, instead of the expected component of <Web />.

I've tried structuring the BrowserRouter in various ways but it makes the most sense to me that Web should be a child of Develop with the route of /develop/web. I've also tried using relative links with no success.

If I change the structure of BrowserRouter so that Web is a direct child (instead of a child of Develop), with a path of /develop/web, the expected component of <Web /> is rendered. Is there an alternative solution?

// index.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { createBrowserRouter, RouterProvider } from "react-router-dom";

import Layout from './routes/Layout';
import ErrorPage from './routes/ErrorPage';
import Home from './routes/Home';
import Develop from './routes/Develop';
import Web from './routes/Web';

const router = createBrowserRouter([
  {
    element: <Layout />,
    errorElement: <ErrorPage />,
    children: [
      {
        path: "/",
        element: <Home />,
      },
      {
        path: "develop",
        element: <Develop />,
        children: [
          {
            path: "web",
            element: <Web />,
          },
        ]
      },
    ]
  }
]);

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);
// Layout.tsx
import { NavLink } from "react-router-dom";

export default function Layout() {
  return (
    <nav>
      <NavLink to={"/"}>
        Home
      </NavLink>
      <NavLink to={"/develop"} end>
        Develop
      </NavLink>
      <NavLink to={"/develop/web"} end>
        Web
      </NavLink>
    </nav>
  )
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
paq
  • 87
  • 8

1 Answers1

2

You need an <Outlet /> to be used in parent route elements to render their child route elements.

React Router Outlet

Bob Junior
  • 36
  • 5