'How to implement authentication for the nested routes in React-Router 6?

I am trying to implement authentication for my routes like this using react-router v6

    <BrowserRouter>
      <Routes>
        <Route path="/auth*" element={<Authentication/>}/>
        {isLoggedIn?
          (< Route path="/" element={<Layout />}>
              <Route path="/tags*" element={<Tags />} />
              <Route path="/meditation*" element={<Meditation/>} />
              <Route path="/settings*" element={<Settings/>} />
              <Route path="/yoga*" element={<Yoga/>} />
          </Route>)
          :(<Navigate to={"/auth/login"} replace={true}/> )
        }
      </Routes>
   </BrowserRouter>

When I am not logged in and try to go to the route "/", it takes me to "/auth/login" as it should, but when I try to go to the nested routes like "/tags", or "/meditation" it gives me a blank screen instead of navigating to "/auth/login". How can I implement authentication for the nested routes?

Thanks in advance.



Solution 1:[1]

Fixed for React Router V6

import React from 'react';
import {Route, Redirect} from 'react-router-dom';

export default function ProtectedRoute({children}){
  const isLoggedIn = LOGICTOCHECKIFUSERISLOGGEDINORNOT;

  return isLoggedIn? <>{children}</>: <Redirect to="/auth/login"/> 
}
<BrowserRouter>
    <Routes>
      <Route path="/auth*" element={<Component1/>}/>
      <Route path="/" element={(
        <ProtectedRoute>
          <Route path="/path1*" element={<Component3/>} />
          <Route path="/path2*" element={<Component4/>} />
          <Route path="/path3*" element={<Component5/>} />
        </ProtectedRoute>
      )} />
    </Routes>
</BrowserRouter>

Solution 2:[2]

Found a solution. You create a component called PrivateRoute like this :

import React from 'react';
import {Route, Navigate} from 'react-router';


interface Props{
  element:any;
  path:string;
  children?:any;
}

export default function ProtectedRoute({element, path, children}:Props){
  const isLoggedIn = LOGICTOCHECKIFUSERISLOGGEDINORNOT;

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

and use it like this :

<BrowserRouter>
      <Routes>
        <Route path="/auth*" element={<Component1/>}/>
        <ProtectedRoute path="/" element={<Component2 />}>
          <Route path="/path1*" element={<Component3 />} />
          <Route path="/path2*" element={<Component4/>} />
          <Route path="/path3*" element={<Component5/>} />
        </ProtectedRoute>
      </Routes>
 </BrowserRouter>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sam
Solution 2 Thor0o0