Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
  • When the Route is not inside <Routes> it gives an error:

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

  • When it is inside <Routes> it give an error as:

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

like image 874
dntfury Avatar asked Sep 13 '25 09:09

dntfury


2 Answers

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

like image 116
Drew Reese Avatar answered Sep 16 '25 00:09

Drew Reese


Here is a private route you can use and its working currently at v6.0.2

export const PrivateRoute = ({ children}) => {
  const isAuthenticated = true;
      
  if (isAuthenticated ) {
    return children
  }
    
  return <Navigate to="/" />
}

This is how you would use the private route

 <Route
          path="/dashboard"
          element={
            <PrivateRoute>
              <Dashboard />
            </PrivateRoute>
          }
        />
like image 28
bilaalsblog Avatar answered Sep 16 '25 00:09

bilaalsblog