React Context with React Router v6.4

40percentironman

Tim Bright

Posted on November 27, 2022

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.

💖 💪 🙅 🚩
40percentironman
Tim Bright

Posted on November 27, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related