-2

I cannot redirect from the Login page to the /profile page after clicking the Login button. How can I fix that?

import React from "react";
import { useHistory } from "react-router-dom";

function Login() {
  const history = useHistory();

  function checkLogin() {
    const loginFormUser = document.getElementById("login-form-user");
    const loginFormPassword = document.getElementById("login-form-password");
    const loginButton = document.getElementById("login-form-submit");
    loginButton.addEventListener("click", () => {
      const username = loginFormUser.username.value;
      const password = loginFormPassword.password.value;

      if (username === "toilacoder" && password === "123456") {
        return history.push("/profile");
      } else {
        return history.push("/home");
      }
    });
  }

  return (
    <form onSubmit={checkLogin}>
      <h2>Please login to get access to your profile.</h2>
      <input type="text" placeholder="Username" id="login-form-user" />
      <input
        type="password"
        placeholder="Your password"
        id="login-form-password"
      />
      <button id="login-form-submit" type="submit">
        Login
      </button>
    </form>
  );
}
export default Login;
Rafael Tavares
  • 5,678
  • 4
  • 32
  • 48
Adam
  • 3
  • 3
  • I'll do that. thanks, sir! – Adam Sep 09 '21 at 14:50
  • Does this answer your question? https://stackoverflow.com/questions/11563638/how-do-i-get-the-value-of-text-input-field-using-javascript remove `.username` and `.password` as its a typo. You can also use refs for this https://reactjs.org/docs/refs-and-the-dom.html – iunfixit Sep 09 '21 at 15:16
  • It did not redirect me to the /profile but it reload and give me "/login?" – Adam Sep 10 '21 at 01:25

1 Answers1

0

You should pass an event argument to your checkLogin function.
You will then use it to prevent the default behavior on form submission by calling the preventDefault function.

Also, the addEventListener was useless, since you are already triggering the checkLogin function on the button click.

Finally, you can retrieve the values from the DOM element without specifying the username and password attributes after you have retrieved the elements with getElementById.

Try to change your code like this:

function checkLogin(e) {
  e.preventDefault();

  const loginFormUser = document.getElementById("login-form-user");
  const loginFormPassword = document.getElementById("login-form-password");

  const username = loginFormUser.value.trim();
  const password = loginFormPassword.value.trim();

  if (username === "toilacoder" && password === "123456") {
    history.push("/profile");
  } else {
    history.push("/home");
  }
}
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29