Responsive Advertisement

How can reset input in a functional component in ReactJS?

 

ReactJS

How can reset input in a functional component in ReactJS?

In a functional component in ReactJS, the value of an input element is typically controlled using the useState hook. To reset the input value, you can update the state value to an empty string or a default value.

Here's an example:

import React, { useState } from 'react';

function Example() {
  const [inputValue, setInputValue] = useState('');

  const handleReset = () => {
    setInputValue('');
  }

  return (
    <div>
      <input value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
      <button onClick={handleReset}>Reset</button>
    </div>
  );
}

In this example, the useState hook is used to create a state variable called inputValue and a function called setInputValue to update the value. The value prop of the input element is set to the inputValue state variable, and the onChange event handler updates the state with the new input value.

The handleReset function updates the inputValue state variable to an empty string when the reset button is clicked. This causes the input element to be reset to its initial value.


Post a Comment

0 Comments