0

I am trying to make my private route redirect the user to the login page when he or she is not authenticated with tokens. When I try to go to home page by changing the url without logging in or registering it goes to a blank white screen instead of going to the login page. This is my code, I am using React Router v6. How can I fix my private route?

//My Private Route
const PrivateRoute = ({ children }) => {
    const navigate = useNavigate();
    const auth = JSON.parse(localStorage.getItem('token'));
    return auth.user ? children : navigate("/login");
}

export default PrivateRoute;

//Render App
function App() {

  return (
    <>
    <ToastContainer/>
    <BrowserRouter>
    <Routes>

    <Route path="/login" element={<Login/>}
    />

    <Route path="/" element={
      <PrivateRoute>
            <Home/>
      </PrivateRoute>
    }
Bqdor
  • 19
  • 5

1 Answers1

0

probably best to return the Navigate component rather than the useNavigate hook:

import {
  Navigate,
  BrowserRouter,
  Routes,
  Route,
} from 'react-router-dom';

//My Private Route
const PrivateRoute = ({ children }) => {
  const auth = JSON.parse(localStorage.getItem('token'));
  return auth?.user ? children : <Navigate to="/login" />;
};
derrmru
  • 61
  • 5