Search code examples
javascriptreactjsreact-router-dom

React Router Dom, redirect with an error message to login page and show the message there


I am using React Router v6 in my application. The user should be redirected to the login page when not logged in and an error message should be shown. So far, the redirection part is working well and it takes the user to the login page. I need to show the authentication required message on the login page.

The code is as follows:

const PrivateRoute = ({ Component }) => {
  const auth = false; //your logic

  return auth ? (
    <Component />
  ) : (
    <Navigate
      to="/login"
      replace={true}
      state={{ alert: "Authentication is required" }}
    />
  );
};

The login component is as follows:

function Login(props) {
  debugger
  return <h1>Login page</h1>;
}

How do I access the error message in the login component? Something like this.props.alert?


Solution

  • You can access it like this:

    import { useLocation } from "react-router-dom";
    

    Then:

    const { state } = useLocation();
    return <div>{state.alert}</div>;