How to reset input fields in React

Last updated on Jun 27, 2021 by Suraj Sharma



In this tutorial, you will learn two ways to reset input fields once clicked on the Reset button in React.


Using controlled components


In controlled components, input values are defined as components local states.


import React from 'react';

const Form = () => {
  const [formValue, setformValues] = React.useState({
    username: '',
    password: ''
  });
  return (
    <form>
      <input value={formValue.username} />
      <input value={formValue.password} />
      <button type="button">Reset</button>
    </form>
  );
}

export default Form;


You can reset the input state values on click of the Reset button by calling the state setter function


import React from 'react';

const ControlledForm = () => {
  const [formValue, setformValue] = React.useState({
    username: '',
    password: ''
  });

  // reset input values
  const handleClick = () => {
    setformValue({
      username: '',
      password: ''
    })
  };

  return (
    <form>
      <input value={formValue.username} name="username" />
      <input value={formValue.password} name="password" />
      <button type="button">Reset</button>
    </form>
  );
}

export default ControlledForm;


Using uncontrolled components


In uncontrolled components, input values are not stored as local states, rather they are directly associated with the dom and its values are updated using the useRef hook.


import React from 'react';

const UnControlledForm = () => {
  const inputRef = React.useRef(null);

  const handleClick = () => {
    // resets the input value
   inputRef.current.value = '';
  };

  return (
    <form>
      <input
        name="username"
        ref={inputRef}
      />

      <button type="button">Reset</button>
    </form>
  );
}

export default ControlledForm;


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.