Home > database >  How to give a provider to a React <Route>?
How to give a provider to a React <Route>?

Time:08-31

I want to provide some data to my React Routes with the help of Provider and my others stores.

  <Router>
    <Routes>
      <Provider store={store}>
        <Route path="/" element={HomePage} />
      </Provider>
      <Provider store={store2}>
        <Route path="/about" element={AboutPage} />
      </Provider>
      <Provider store={store3}>
        <Route path="/review" element={ReviewPage} />
      </Provider>
    </Routes>
  </Router>

But when I run my app it gives me the next error : [Provider] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>.

How can use my provider inside my Routes?

CodePudding user response:

You need to change the structure and wrap your Router inside each Provider as you can't have anything else than Route inside component.

Also in React Router Dom V6, you need to render the element eg <Homepage />

The code can look like this:

<>
  <Provider store={store}>
     <Router>
       <Routes>
           <Route path="/" element={<HomePage />} />
       </Routes>
     </Router>
   </Provider>
   <Provider store={store2}>
     <Router>
       <Routes>
           <Route path="/about" element={<AboutPage />} />
       </Routes>
     </Router>
   </Provider>
  </>

The latest update was to render the 'element' in eact-router-dom V6 as pointed out by @Ergis in the comments

  • Related