How do i wrap 2 Routes with a context in React router v6

Viewed 461

how do i wrap 2 routes in a context in react router v6? only these two should be exposed to that context and i cant set the context separately because the context runs some code(useEffect) and if i do that it triggers everytime i switch route, i want it to trigger before i load the 2 routes not after pressing them, but also after i load app.js so app.js loads and the context provider doesnt, then when i one of the 2 routes the context triggers, and when i switch between them it wont trigger is it possible? thanks

  return (
    <Layout>
      <Routes>
        <Route path="/*" element={<Navigate replace to='/login'/>} />
        <Route path="/pracels" element={<PracelsPage/>} />
        <Route path="/search" element={<SearchPracelPage/>} />
        <Route path="/login" element={<LoginPage/>} />
      </Routes>
    </Layout>
  );

i want to wrap /pracels and /search with 1 context provider

2 Answers

In react-router-dom@6 you can create what are called layout routes to render the context provider and provide a context value to a set of routes. These are generally pathless route components that provide common functionality to a set of routes, each matched and rendered into an Outlet component rendered by the layout.

Basic example:

import { Outlet } from 'react-router-dom';

const MyContextLayout = () => {
  ...

  return (
    <MyContextProvider>
      <Outlet />
    </MyContextProvider>
  );
};

export default MyContextLayout;

...

import MyContextLayout from '../path/to/MyContextLayout';

...

return (
  <Layout>
    <Routes>
      <Route path="/*" element={<Navigate replace to='/login'/>} />
      <Route element={<MyContextLayout />}>
        <Route path="/pracels" element={<PracelsPage/>} />
        <Route path="/search" element={<SearchPracelPage/>} />
      </Route>
      <Route path="/login" element={<LoginPage/>} />
    </Routes>
  </Layout>
);

You can just wrap the routes in one context provider.

Lets say you have a context called AuthProvider you can use it like this:

return (
    <Layout>
     <AuthProvider>
        <Routes>
         <Route path="/pracels" element={<PracelsPage/>} />
         <Route path="/search" element={<SearchPracelPage/>} />
      </Routes>
      </AuthProvider>
      <Routes>
          <Route path="/*" element={<Navigate replace to='/login'/>} />
          <Route path="/login" element={<LoginPage/>} /> 
      <Routes/>      
    </Layout>
  );

Now only the routes in <AuthProvider> will use your context.

Related