Home > Software design >  can i use useRef hook to empty the input value?
can i use useRef hook to empty the input value?

Time:10-16

I need to empty the input field when click submit button

I want to know how to empty the input when controlling several useRefs as one

like inputRef.current.value = ""

here is the Code

function SignUp() {
  const ref = useRef();

  const onChange = (e) => {
    ref.current = { ...ref.current, [e.target.name]: e.target.value };
  };

  const handleSignUpClick = () => {
    // I Need To Empty input value here
  };

  return (
      <form onSubmit={(e) => e.preventDefault()}>
        <input
          type="text"
          name="email"
          onChange={onChange}
        />
        <input
          type="password"
          name="password"
          onChange={onChange}
        />

        <button
          onClick={handleSignUpClick}
        >
          Sign up
        </button>
      </form>
  
  );
}

export default SignUp;

CodePudding user response:

Better way would be to use useState.

function SignUp() {
  const ref = useRef();

  const onChange = (e) => {
    ref.current = { ...ref.current, [e.target.name]: e.target.value };
  };

  const handleSignUpClick = (e) => {
    e.preventDefault();
    // I Need To Empty input value here
    e.target.reset();
  };

  return (
      <form onSubmit={handleSignUpClick}>
      <input type="text" name="email" onChange={onChange} />
      <input type="password" name="password" onChange={onChange} />

      <button>Sign up</button>
    </form>
  
  );
}

export default SignUp;
  • Related