Home > Software engineering >  React Router V6 routed component needs state/props from another routed component
React Router V6 routed component needs state/props from another routed component

Time:06-12

Hello I am using React router for my application. App.js code segment:

  <Routes>
    <Route path="/" element={<Login navigate={navigate} setOverlays={setOverlays} setToken={setToken} setUser={setUser} />} />
    <Route path="/create-account" element={<CreateAccount />} />
    <Route path="/projects" element={<Projects token={token} name={user.name} jobTitle={user.jobTitle} navigate={navigate} setOverlays={setOverlays} />} />
    <Route path="/individual_project" element={<IndividualProject />} />
  </Routes>

The last route (/individual_project) requires props that is located in the projects component. Since I do not have access to the components in App.js how can I create this route.

I also prefer not to move the state variables from the Projects component and pass them down through props.

CodePudding user response:

There are few ways to achieve that:

  • You can move the individual_project route inside the Projects component like this:
const Projects = () => {
...other logic
return(
 <Routes>
   <Route path="/individual_project" element={<IndividualProject />} />
 </Routes>
)
}

Docs here: https://reactrouter.com/docs/en/v6/getting-started/overview#nested-routes

  • Alternatively, you could also create a context to wrap the routes. Then, you can retrieve the variables directly from the context:
<Context.Provider value={yourValuesToShare}>
 <Routes>
    <Route path="/" element={<Login navigate={navigate} setOverlays={setOverlays} setToken={setToken} setUser={setUser} />} />
    <Route path="/create-account" element={<CreateAccount />} />
    <Route path="/projects" element={<Projects token={token} name={user.name} jobTitle={user.jobTitle} navigate={navigate} setOverlays={setOverlays} />} />
    <Route path="/individual_project" element={<IndividualProject />} />
 </Routes>
</Context.Provider>

Docs here: https://reactjs.org/docs/context.html

CodePudding user response:

For this kind of scenarios , using Context API is recommended .its more precise and cleaner that the other techniques. React docs

CodePudding user response:

Context api is used to access state from any component so react context api is recommended

  • Related