DEV Community

Tim Bright
Tim Bright

Posted on

React Context with React Router v6.4

I searched for a while to find how to use the Context API with createBrowserRouter. What I found is that you can use layout routes to wrap your components with the provider:

import { Outlet } from 'react-router-dom';
export default function ContextLayout() {
  return (
    <ContextProvider>
      <Outlet />
    </ContextProvider>
  );
};
Enter fullscreen mode Exit fullscreen mode

Then, you can create a RouteObject without a path that renders that layout route with the children as the components you want to wrap in the provider.

import { createBrowserRouter, RouterProvider } from 'react-router-dom';
const router = createBrowserRouter([
  {
    element: <ContextLayout />,
    children: [
      {
        path: '/some/path',
        element: <SomeContextConsumer />
      }
    ]
  },
  ...
]);

export default () => {
  const rootElement = document.getElementById('root');
  const root = createRoot(rootElement!);
  root.render(
    <RouterProvider router={router} />
  );
};
Enter fullscreen mode Exit fullscreen mode

That's it! Hopefully this saves someone the time it took me to figure this out.

Top comments (0)