How to clear input field value on button click in react?

Hi Friends πŸ‘‹,

Welcome To aGuideHub! ❀️

Today, I am going to show you. How to clear input field value on button click in react with code example.

Let’s look at the following example to understand how it basically works:

APP.js

import {useState} from 'react';

const App = () => {
  // πŸ‘‡οΈ store input's value in state
  const [message, setMessage] = useState('');

  const handleChange = event => {
    setMessage(event.target.value);
  };

  const handleClick = () => {
    // πŸ‘‡οΈ clear input value
    setMessage('');
  };

  return (
    <div>
      <input
        id="message"
        name="message"
        type="text"
        onChange={handleChange}
        value={message}
      />

      <button onClick={handleClick}>Clear field</button>
    </div>
  );
};

export default App;

We used the useState hook to store the value of the input field in a state variable.

The handleClick function we passed to the onClick prop of the button element gets called every time the button is clicked.

Check the output of the above code example.

React App, clear-input-field-value-on-button

React App, clear-input-field-value-on-button

All the best πŸ‘

Follow me on Twitter