Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

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>
  );
};
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #How #handle #protected #routes #React #redirect #user #original #URL #visited
ADD COMMENT
Topic
Name
8+9 =