DEV Community

Tim Bright
Tim Bright

Posted on

1 1

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.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay