Answers for "How to handle protected routes in React plus redirect user to original URL being visited"

0

How to handle protected routes in React plus redirect user to original URL being visited

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

export const ProtectedRoute = ({ role, ...rest }) => {
  const currentRole = JSON.parse(localStorage.getItem("role"));
  if (currentRole === role) {
    return <Route {...rest} />;
  } else {
    return (
      <Redirect
        to={{
          pathname: currentRole ? "/" : "/login",
          state: {
            from: rest.location
          }
        }}
      />
    );
  }
};


// Login Component (handled redirection to the URL being accessed)
import { useHistory, useLocation } from "react-router-dom";

const Login = () => {
  const history = useHistory();
  const { state } = useLocation();

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const onSubmit = (email, password) => {
    const user = loginData.find(
      (el) => el.email === email && el.password === password
    );

    if (user) {
      localStorage.setItem("role", JSON.stringify(user.access));
      history.replace(state.from ?? "/");
    } else {
      console.error("no user match found!");
    }
  };

  return (
    <div>
      ....
    </div>
  );
};
Posted by: Guest on March-03-2022

Code answers related to "How to handle protected routes in React plus redirect user to original URL being visited"

Code answers related to "Javascript"

Browse Popular Code Answers by Language