reactjsreact-routerreact-router-dom

How to use Private route in react-router-dom@v6


I want to use private route with react-router-dom v6, while i am trying to apply a condition for auth.

In App.js

<Route path='/dashboard' element= { <PrivateRoute><Abc /></PrivateRoute>}/>

In a component .js

<Routes> <Route {...rest} render={props => !isAuthenticated && !loading ? (<Navigate to='/login' />) : (<Component {...props} />)} /></Routes>

Error: A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your in a <Routes>

Error: [Abc] is not a <Route> component. All component children of must be a <Route> or <React.Fragment>

Pls help me to resolve this situation ? Or any suggestion.

Tried this but one of the above error in both cases

<Route path='/dashboard' element= {<PrivateRoute> <Dashboard />
         </PrivateRoute>}/>

Also

<PrivateRoute path='/dashboard' element= { <Dashboard />}/>

PICCode full


Solution

  • In react-router-dom version 6 there is no render prop for the Route component. You can also simplify your PrivateRoute wrapper component a bit, it doesn't need to render more Routes and Route components.

    Conditionally render the component's children or navigate to log in.

    const PrivateRoute = ({ auth: { isAuthenticated }, children }) => {
      return isAuthenticated ? children : <Navigate to="/login" />;
    };
    

    Usage:

    <Route
      path="/dashboard"
      element={
        <PrivateRoute>
          <Dashboard />
        </PrivateRoute>
      }
    />
    

    A slightly improved version to allow nesting more private route components utilizes an outlet to handle rendering out nested routes.

    const PrivateWrapper = ({ auth: { isAuthenticated } }) => {
      return isAuthenticated ? <Outlet /> : <Navigate to="/login" />;
    };
    

    Usage:

    <Route element={<PrivateWrapper />}>
      <Route path="/dashboard" element={<Dashboard />} />
    </Route>
    

    Edit how-to-use-private-route-in-react-router-domv6