react clear input after button click

How to React Clear Input After Button Click

Clearing an input field after a button click is a common requirement in web development. In React, there are multiple ways to achieve this. Let's take a look at two ways to clear input fields after a button click.

Method 1: Controlled Component with State

The first method involves using a controlled component with state management in React. A controlled component is an input form element whose value is controlled by React.

We start by creating a state variable that will hold the value of the input field. We then attach an onChange event handler to the input field that updates the state variable with the current value of the input field. Finally, we attach an onClick event handler to the button that sets the state variable to an empty string, which effectively clears the input field.


import React, { useState } from "react";

function ClearInput() {
  const [inputValue, setInputValue] = useState("");

  const handleInputChange = (event) => {
    setInputValue(event.target.value);
  };

  const handleButtonClick = () => {
    setInputValue("");
  };

  return (
    
      
      Clear Input
    
  );
}

Method 2: Uncontrolled Component with Ref

The second method involves using an uncontrolled component with a ref in React. An uncontrolled component is an input form element whose value is controlled by the DOM.

We start by creating a ref that will reference the input field. We then attach an onClick event handler to the button that sets the value of the input field to an empty string using the ref.


import React, { useRef } from "react";

function ClearInput() {
  const inputRef = useRef(null);

  const handleButtonClick = () => {
    inputRef.current.value = "";
  };

  return (
    
      
      Clear Input
    
  );
}

Both of these methods are valid ways to clear input fields after a button click in React. The controlled component method is recommended for most cases, but the uncontrolled component method can be useful in certain situations, such as when dealing with input fields that need to be reset to their default values.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe