Search code examples
react-routerreact-router-dom

How do I make a component both a child of BrowserRouter and a parent of all routes in React Router v6 (function syntax)?


In React Router v6, you can use components to define the router, like this:

export default () => (
  <BrowserRouter>
    <MyProvider>
      <Routes>
        ...
      </Routes>
    </MyProvider>
  </BrowserRouter>
);

Where the MyProvider component is able to wrap all of the routes, while also being a child of the BrowserRouter component (so it is able to use React Router hooks like useNavigate()).

But how do you replicate this using the function syntax, i.e.,

const router = createBrowserRouter([
  ...
]);

export default () => (
  <RouterProvider router={router} />
);

Solution

  • Create a layout route that renders the provider component and an Outlet as its child, and all the nested routes it wraps will be rendered into the outlet under the context it provides.

    Example:

    const MyProviderLayout = () => (
      <MyProvider>
        <Outlet />
      </MyProvider>
    );
    
    const router = createBrowserRouter([
      ...
      {
        element={<MyProviderLayout />}
        children: [
          ... routes that access the `MyProvider` context ...
        ],
      },
      ... other routes ...
    ]);
    
    export default () => (
      <RouterProvider router={router} />
    );