More than one context with different Routes with React Router 6

Viewed 158

I am playing (and learning about) with Context API and React Router (v6), and having problems when I want to wrap some components inside one context, but not all of them.

right know, I have this structure in my App.js and is working fine :

<AuthContextProvider>
        <Nav />
        <CharactersContextProvider>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="characters" element={<Characters />} />
            <Route path="about" element={<About />} />
            <Route path="characters/:name" element={<Details />} />
            <Route path="about/:id" element={<MoreAbout />} />
          </Routes>
        </CharactersContextProvider>
</AuthContextProvider>

I would like to NOT give access to <MoreAbout> to </CharactersContextProvider>

And I was simply restructuring it like this :

<AuthContextProvider>
        <Nav />
        <CharactersContextProvider>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="characters" element={<Characters />} />
            <Route path="about" element={<About />} />
            <Route path="characters/:name" element={<Details />} />
          </Routes>
        </CharactersContextProvider>
        <Routes>
          <Route path="about/:id" element={<MoreAbout />} />
        </Routes>
</AuthContextProvider>

Obviously it is not the way, since React is giving me many warnings saying that no Routes matched the 4 paths inside the first Routes: No routes matched Location "/" / "/about" / " /characters" Not only that, but if I go to <Characters>, and then to <MoreAbout>, I still have access to the data stored in </AuthContextProvider>. And that i don't understand why.

What would be the right way to have some components have access to a context provider, and others not, when having 2 contexts? is it possible keeping them all inside App.js ?

Thanks in advance for any reply.

0 Answers
Related