Code for how to clear textbox in react js ,2024

To clear a textbox in React, you can use the useState hook to keep track of the textbox value and update it when needed. Here’s an example:

import React, { useState } from 'react';

function TextBox() {
  const [text, setText] = useState('');

  const handleClear = () => {
    setText('');
  }

  return (
    <div>
      <input type="text" value={text} onChange={(e) => setText(e.target.value)} />
      <button onClick={handleClear}>Clear</button>
    </div>
  );
}

In this example, we’re using the useState hook to create a state variable text and a function setText to update it. We’re also creating a handleClear function that sets the text state variable to an empty string when the “Clear” button is clicked.

The textbox value is set to the text state variable using the value prop on the input element. The onChange event updates the text state variable whenever the user types in the textbox.

The “Clear” button calls the handleClear function when clicked, which clears the textbox by setting the text state variable to an empty string.

Discover more from STRUGGLER KING.COM

Subscribe now to keep reading and get access to the full archive.

Continue Reading