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

Solution 1:

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

Solution 2:

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>
          }
        />