'can not get input value using useRef in react hook form
I am using react hook form to make a login form .I am trying get the input value of email, after i click on reset button. so i used useRef. But useRef is not setting the current value on the current object, after i click the reset button. Why is it not working?
const Login = () => {
const emailRef = useRef("");
const {
register,
formState: { errors },
handleSubmit,
} = useForm();
const handleResetPass = async () => {
const email = emailRef.current.value;
console.log(email);
};
return (
<section>
<div>
<div>
<h2>Login</h2>
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label>
<span>Email</span>
</label>
<input
type="email"
placeholder="Your email"
ref={emailRef}
{...register("email", {
required: {
value: true,
message: "Email is required",
},
pattern: {
value: /[a-z0-9]+@[a-z]+\.[a-z]{2,3}/,
message: "Provide a valid email",
},
})}
/>
<label>
{errors.email?.type === "required" && (
<span className="label-text-alt text-red-500">
{errors.email.message}
</span>
)}
{errors.email?.type === "pattern" && (
<span className="label-text-alt text-red-500">
{errors.email.message}
</span>
)}
</label>
</div>
</form>
<p>
<small>
Forgotten password ?{" "}
<button
onClick={handleResetPass}
>
Reset
</button>
</small>
</p>
</div>
</div>
</section>
);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|