Home > Software design >  How to make default route to login page if not authenticated react-router-dom
How to make default route to login page if not authenticated react-router-dom

Time:01-24

I have an application where the first thing(default route) a user sees is a landing page with a register or login form if that user is not authenticated, if a user is authenticated I want to show the dashboard, (similar to how social media works) I have created 2 layouts <IsAuthenticated /> (where i render everything i want user that is authenticated to see) and an <Authentication /> (where i render the landing page with register and login forms), i'm having a really hard time making the logic how to use react router with this, If you know a tutorial suggestion where they handle this type of routing would be great

CodePudding user response:

You can do something like this

export const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
    {...rest}
    render={(props) =>
        isLogin ? (
            <Component {...props} />
        ) : (
            <Redirect
                to={{
                    pathname: '/',
                    state: { from: props.location },
                }}
            />
        )
    }
/>

);

CodePudding user response:

This function will redirect to the login page if the user isn't authenticated (change your AuthContext according to yours).

You can do the opposite for public route that shouldn't be accessible if the user is logged in (the login page for exemple).

const PrivateRoute = (props) => {
    const { children } = props;
    let auth = useContext(AuthContext);
    let location = useLocation();

    if (!auth.isLoggedIn) {
        return <Navigate to="/login" state={{ from: location }} replace />;
    }

    return <>{children}</>;
};

In your routes :

<Route
    path="/MY_SECRET_ROUTE"
    element={
        <PrivateRoute>
            <MySecretComponent />
        </PrivateRoute>
    }
>
  •  Tags:  
  • Related