Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset button does not clear inputs in React

I have this simple form in my App form. I learned that a button with type="reset" clears the inputs, but it isn't working here with React. Am I missing something?

import { useState } from "react";

export default function App() {
  const [name, setName] = useState("");
  return (
    <form>
      <input
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Name"
        name="name"
      />
      <button>Submit</button>
      <button type="reset">Reset</button>
    </form>
  );
}

1 Answers

You must reset the state name with an empty string when the reset button is clicked.

export default function App() {
  const [name, setName] = useState("");

  const onClickReset = () => setName('');
  
  return (
    <form>
      <input
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Name"
        name="name"
      />
      <button>Submit</button>
      <button type="reset" onClick={onClickReset}>Reset</button>
    </form>
  );
}
like image 174
R.M. Reza Avatar answered May 25 '26 21:05

R.M. Reza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!