by Sai gowtham

Clearing the input field value in React

In this tutorial, we are going to learn about how to clear an input field value in react by clicking a form submit button.

We mostly clear the input field values whenever we submit a form or resetting the cluttered form.

Clearing the input field values

If you are using controlled components, it means your form (input) data is controlled by the react state, so that you can clear an input field value by assigning an empty string '' to the react state.

Here is an example:

Login.js
import React, { useState } from "react";

export default function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  function handleSubmit(e) {
    e.preventDefault();
    console.log(email, password);
    // clearing the values
    setEmail("");    setPassword("");  }

  return (
    <form>
      <input
        type="email"
        placeholder="Email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <input
        type="password"
        placeholder="Password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <button type="submit" onClick={handleSubmit}>        Login      </button>    </form>
  );
}

In the above example, we are clearing the email, password input field values whenever a user clicks on the login button.

Similarly, if you are using uncontrolled components where your form input data is handled by dom itself instead of react state where you can clear it like this.

Login.js
import React from "react";

export default function Login() {
  function handleSubmit(e) {
    e.preventDefault();
    console.log(this.email.value, this.password.value);

    // clearing the values
    this.email.value = "";    this.password.value = "";  }

  return (
    <form>
      <input
        type="email"
        placeholder="Email"
        ref={(el) => (this.email = el)} />      <input
        type="password"
        placeholder="Password"
        ref={(el) => (this.password = el)}      />
      <button type="submit" onClick={handleSubmit}>
        Login
      </button>
    </form>
  );
}

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course