Home > Software design >  react-router-dom passing useState for reusing other routes
react-router-dom passing useState for reusing other routes

Time:07-22

So I can't see something react-hooks related here and I don't get the logic a little bit in react component with those passing state in routes.

So basically something like this.

      <Router>
        <Navbar></Navbar>
        <Routes>
          <Route path="/guest" element={<Guest></Guest>}></Route>
          <Route path="/saved" element={<SavedItem></SavedItem>}></Route>
          <Route path="/selectedgallery" element={<SelectedGallery></SelectedGallery>}></Route>
          <Route path="/selectedsavedgallery" element={<SelectedSaveGallery></SelectedSaveGallery>}></Route>
          <Route path="/login" element={<Login></Login>}></Route>
          <Route path="/register" element={<Register></Register>}></Route>
          <Route path="/" element={<Gallery></Gallery>}></Route>
          <Route path="/create" element={<CreatePin></CreatePin>}></Route>
        </Routes>
      </Router>

As you see I have <Login> and what I want to do I will pass my useState() in that area and when I get the user I will pass it in my other routes so I could reuse it for users that have login.

I imagine it somehow look like this

    const [owner,setOwner] = useState()
    
    ...
   <Route path="/login" element={<Login></Login>} {whatever here to pass the "setOwner" and "owner".} ></Route>
    ...

then I will used it here in a routes /saved,/create,/selectedsavedgallery just incase if the user is not login and I will redirect it to /login router or /register. But I got lack of information.

CodePudding user response:

setOwner can be passed to the Login element as an parameter

<Route path="/login" element={<Login setOwner={setOwner}/>} />

in Login

function Login({setOwner}) {
  ...
  setOwner("foo");
  ...
}
  • Related