Home > Software engineering >  Protected Routes - react-router-dom v6
Protected Routes - react-router-dom v6

Time:07-13

I am following this to implement protected routes, however, I am getting a very weird bug.

Depending on how I write my conditional, the component doesn't get re-rendered. Below is the code:

export const LoginRequired = ({ isAuthenticated, children }) => {
    if (isAuthenticated) {
        return <Navigate to='/' replace /> // isAuthenticated state changes detected
        // return children <- isAuthenticated state changes not detected
    }
    // return <Navigate to='/' replace /> <- isAuthenticated state changes not detected
    return children; // isAuthenticated state changes detected
}

I want the children to be rendered if isAuthenticated is true. However, when I have that block of code uncommented, the state changes aren't detected.

I'm not too sure why this is not working as I have the exact same code for a different route.

export const ProtectedRoute = ({ isAuthenticated, children }) => {
    if (isAuthenticated) {
        return <Navigate to='/' replace />
    }
    return children;
}

Am I missing something?

Thanks.

CodePudding user response:

The issue you are having is you need to add a not (!) operator in front of the isAuthenticated variable.

I would also recommend changing the Navigate component and use a useNavigation hook instead. This is typically preferred unless in a class component where you cant use hooks.

export const ProtectedRoute = ({ isAuthenticated, children }) => {
   const navigate = useNavigate();
    if (!isAuthenticated) { //Check not authenticated
         navigate("/", { replace: true });
    }
    return children;
}
  • Related