Home > Net >  how can I add condition in route in v6 of react-router-dom in react.js?
how can I add condition in route in v6 of react-router-dom in react.js?

Time:08-22


    <Router>
          <Routes>
            <Route path='/' {user && user._id ? element={<Homepage/>} : element={<Login/>}}>
            
            <Route path='/login' element={<Login/>}/>
            <Route path='/register' element={<Register/>}/>
          </Routes>
        </Router>

How can I write code? The homepage will only render when the user is logged in.

Basically, I have created a login and registration website, when I add a path in the URL (localhost:3000/home), The homepage opens. What I want is to show the homepage only when the user logged in. Not just by typing (localhost:3000/homepage).

CodePudding user response:

You need pass element prop with Component Homepage or Login as flow

<Route path='/' element={user && user._id ? <Homepage/> : <Login/>}>

CodePudding user response:

This is one possible approach for redirecting visitors to the correct page when they are logged in/not logged in and attempt to view a page that they are not permitted to access:

const isLoggedIn = user && user._id;

return (
  <Routes>
    <Route
      path="/"
      element={
        isLoggedIn ? (
          <Navigate to="/home" replace />
        ) : (
          <Navigate to="/login" replace />
        )
      }
    />

    <Route
      path="/home"
      element={isLoggedIn ? <Home /> : <Navigate to="/login" replace />}
    />

    <Route
      path="/login"
      element={!isLoggedIn ? <Login /> : <Navigate to="/home" replace />}
    />

    <Route
      path="/register"
      element={!isLoggedIn ? <Register /> : <Navigate to="/home" replace />}
    />
  </Routes>
);
  • Related