简体   繁体   中英

How can I redirect login to current page in react js?

I create a single page application using react. I create protected route but after login, I can access login page after login. If I try to go login route I can access. How can I prevent to this. If I try to access login page It will redirect login to my current page.

This is assuming you're using react-router, but you essentially want to be able to check if the user is logged in, and if they are then you want to conditionally remove the <Route... definition for login.

example:

export function App() {
return (
  <Routes>
    <Route path="/" element={<DataPipelineEditorView />} />
    {isUserLoggedIn ? null : <Route path="/login" element={<Login />} />}
  </Routes>
}

You'll just need to figure out how to populate the isUserLoggedIn . If you have a react context (or some other means) that holds the state of your user's login session (or maybe a local storage cookie) you can check it in the component and render the Routes accordingly.

If you're not using react router then share your code and we can go from there!

you can use

  Router,
  Switch,
  Route,
  Link

for it.

here I put a example for route example, hope it will help you.

This is my login page logic, hope this help you by using 'history.goBack()'

import { useState, useEffect } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import "./LoginScreen.css";

const LoginScreen = ({ history }) => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  
  const history = useHistory();

  useEffect(() => {
    if (localStorage.getItem("authToken")) {
      history.goBack(); // or try history.push("/");
    }
  }, [history]);

  const loginHandler = async (e) => {
    e.preventDefault();

    const config = {
      header: {
        "Content-Type": "application/json",
      },
    };

    try {
      const { data } = await axios.post(
        "/api/auth/login",
        { email, password },
        config
      );

      localStorage.setItem("authToken", data.token);
        
        // After logged in, redirect to route that was before login route:
      
      history.goBack();
    } catch (error) {
      setError(error.response.data.error);
      setTimeout(() => {
        setError("");
      }, 5000);
    }
  };

  return (
    <div className="login-screen">
      <form onSubmit={loginHandler} className="login-screen__form">
        <h3 className="login-screen__title">Login</h3>
        {error && <span className="error-message">{error}</span>}
        <div className="form-group">
          <label htmlFor="email">Email:</label>
          <input
            type="email"
            required
            id="email"
            placeholder="Email address"
            onChange={(e) => setEmail(e.target.value)}
            value={email}
            tabIndex={1}
          />
        </div>
        <div className="form-group">
          <label htmlFor="password">
            Password:{" "}
            <Link to="/forgotpassword" className="login-screen__forgotpassword">
              Forgot Password?
            </Link>
          </label>
          <input
            type="password"
            required
            id="password"
            autoComplete="true"
            placeholder="Enter password"
            onChange={(e) => setPassword(e.target.value)}
            value={password}
            tabIndex={2}
          />
        </div>
        <button type="submit" className="btn btn-primary">
          Login
        </button>

        <span className="login-screen__subtext">
          Don't have an account? <Link to="/register">Register</Link>
        </span>
      </form>
    </div>
  );
};

export default LoginScreen;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM