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 value of the value attribute to an empty string.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [val, setVal] = useState();

  return (
    <div>
      <input type="text" value={val} />
      <button onClick={() => setVal(() => "")}>Reset</button>
    </div>
  );
}

We create the val state with the useState hook.

Then we set the value prop of the input to the val state.

Next we set the onClick prop of the button to a function that calls setVal to an empty string.

Now when we type in something and click Reset, we see the input box emptied.

Conclusion

To clear an input field with React, we can set the value of the value attribute to an empty string.

By John Au-Yeung

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

3 replies on “How to Clear an Input Field with React?”

Hello, when I use this code I can write on the input again, Ive found that adding an extra line defining “setVal(() => null)” allows me to write again

Do you have any other solution ?

Leave a Reply

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