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.

Leave a Reply

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