Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear value into input using useState or useRef (React)

I got hook:

const [myName, setMyName] = useState("");
const myNameRef = useRef();

Then I have form:

<form onSubmit={(e) => addVist(e, user.id)}>
 <input type="text" name="myName" ref={myNameRef} onChange={e => setMyName(e.target.value)} />
 <input type="submit" value="Run" />
</form>

And method:

const addVist = (e, userId) => {
        e.preventDefault();

        console.log(myName)
        //some code....

        //clear value form
        setMyName("");
        //setMyName('');
        //setMyName(e.target.value = "");
        //myNameRef.current.value("");

    }

But the setMyName("") is not working - still I see value inside input.

like image 546
4est Avatar asked Jul 13 '26 17:07

4est


2 Answers

Here is a complete example of clearing input using state OR a reference:

export default function App() {
  const [value, setValue] = useState("");
  const inputRef = useRef();
  return (
    <>
      <input value={value} onChange={(e) => setValue(e.target.value)} />
      <input ref={inputRef} />
      <button
        onClick={() => {
          setValue("");
          inputRef.current.value = "";
        }}
      >
        Clear
      </button>
    </>
  );
}

Refer to Controlled VS Uncontrolled components.

like image 173
Dennis Vash Avatar answered Jul 17 '26 19:07

Dennis Vash


You missed binding myName as value attribute of the input tag.

 <input type="text" name="myName" value={myName} ref={myNameRef} onChange={e => setMyName(e.target.value)} />
like image 25
wangdev87 Avatar answered Jul 17 '26 20:07

wangdev87



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!