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

2

10

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

Naked answered 26/6, 2022 at 18:2 Comment(0)
N
21

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>
);
Nascent answered 28/6, 2022 at 2:52 Comment(0)
G
2

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.

Guntar answered 26/6, 2022 at 18:9 Comment(1)
I guess you're right in v6 so we need to put the Context component outisde of the routes and then you can use another routes component to register more routes. I've updated my answserGuntar

© 2022 - 2024 — McMap. All rights reserved.