Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset input field from useRef in React?

I have a text input. If I click on a specific button in the page, I want to reset the value of the input. Here is my code:

const inputRef = useRef()

const handleClick= () => {
 inputRef.current.value.reset();
 return "hello world"
}

return (
<>
<input type="text" ref={inputRef}/>
<button onClick={()=> handleClick}>delete all</button>
</>
)

It doesn't work. How to fix this?

like image 908
DoneDeal0 Avatar asked Nov 18 '25 20:11

DoneDeal0


2 Answers

reset is available on form element. You can wrap your input with a form, and trigger reset on it.

const {useRef} = React;
const App = () => {
  const formRef = useRef();

  const handleClick = () => {
    formRef.current.reset();
  };

  return (
    <form ref={formRef}>
      <input type="text" />
      <input type="password" />
      <input type="checkbox" />
      <textarea></textarea>
      <button onClick={handleClick} type="button">
        clear form
      </button>
    </form>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>

<div id="root"></div>
like image 147
felixmosh Avatar answered Nov 21 '25 09:11

felixmosh


You can clear the value in the input field like below.

const handleClick= () => {
 inputRef.current.value = "";
 return "hello world"
}

and change onClick call in the button like below

onClick={handleClick}
//or
onClick={()=> handleClick()}

If you want complete reset of a form having multiple inputs, you can follow the below approach. In below example, form will reset after submit


const formRef = useRef();

const handleClick = () => { 
  formRef.current.reset();
}

render() {
  return (
    <form ref={formRef}>
      <input />
      <input />
      ...
      <input />
    </form>
  );
}

if you don't want to use Ref

const handleSubmit = e => {
 e.preventDefault();
 e.target.reset();
}

<form onSubmit={handleSubmit}>
  ...
</form>
like image 26
harish kumar Avatar answered Nov 21 '25 09:11

harish kumar



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!