How to submit a login form in React using React hook

Last updated on Nov 15, 2020 by Suraj Sharma



In this tutorial, you will learn how you can submit a login form or any other html form in React using <form> onSubmit attribute


Consider, we have created a controlled function component <LoginForm /> that renders a form with two <input /> fields and a login <button />


import React from 'react';

const LoginForm = () => {
  
  const [formValue, setformValue] = React.useState({
    email: '',
    password: ''
  });

  const handleSubmit = (event) => {}

  const handleChange = (event) => {}

  return (
    <form onSubmit={handleSubmit}>
      <p>Login Form</p>
      <input
        type="email"
        name="email"
        placeholder="enter an email"
        value={formValue.email}
        onChange={handleChange}
      />
      <input
        type="password"
        name="password"
        placeholder="enter a password"
        value={formValue.password}
        onChange={handleChange}
      />
      <button
        type="submit"
      >
        Login
      </button>
    </form>
  )
};

export default LoginForm;

The <LoginForm /> has a local state formValue that stores the email and password, defined using useState() React hook


The handleChange event handler updates the formValue state every time the input fields value changes


const handleChange = (event) => {
  setformValue({
    ...formValue,
    [event.target.name]: event.target.value
  });
};


The handleSubmit() event handler gets called when we submit the form by clicking on the login button.


Our logic of making an authentication API call goes inside the handleSubmit().



const handleSubmit(event) {
  event.preventDefault();
  const { email, password } = formValue;
  if (email && email.trim() && password && password.trim()) {
    // make an authentication api call here
  }
}


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.