Categories
React Answers

How to Clear an Input Field with React?

Spread the love

Sometimes, we want to clear an input field with React.

In this article, we’ll look at how to clear an input field with React.

Clear an Input Field with React

To clear an input field with React, we can set the state that’s used as the input value to an empty string.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [firstName, setFirstName] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    if (firstName) {
      console.log(firstName);
      setFirstName("");
    }
  };

  return (
    <>
      <form onSubmit={handleSubmit}>
        <label htmlFor="firstName">Name </label>
        <input
          type="text"
          value={firstName}
          onChange={(e) => setFirstName(e.target.value)}
        />
        <button type="submit">add person</button>
      </form>
    </>
  );
}

We have the firstName state that we created with the useState hook. It’s set as the value of the value prop of the input.

Then we have the handleSubmit function that calls e.preventDefault to prevent server-side form submission.

And we call setFirstName with an empty string to clear the input.

Next, we have an input with the onChange prop set to a function that calls setFirstName with e.target.value to set the firstName state to the inputted value.

And we set onSubmit prop to handleSubmit to call it when we click on the button.

Conclusion

To clear an input field with React, we can set the state that’s used as the input value to an empty string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *