Last active
January 17, 2022 16:33
-
-
Save KolbySisk/a4c141bbc52a8a0937646f6020d585af to your computer and use it in GitHub Desktop.
React Hook Form Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useForm } from "react-hook-form"; | |
export default function RhfForm() { | |
const { | |
register, | |
handleSubmit, | |
reset, | |
formState: { errors } | |
} = useForm(); | |
const processForm = async (data) => { | |
await fetch("/api/form", { | |
method: "POST", | |
body: JSON.stringify(data) | |
}); | |
reset(); | |
}; | |
return ( | |
<form | |
onSubmit={handleSubmit(processForm)} | |
style={{ display: "flex", flexDirection: "column", width: 300 }} | |
> | |
<input | |
{...register("email", { required: true })} | |
name="email" | |
type="email" | |
/> | |
{errors.email && <span>Email is required </span>} | |
<input | |
{...register("password", { required: true, minLength: 6 })} | |
name="password" | |
type="password" | |
/> | |
{errors.password && ( | |
<span>Password is required and must be at least 6 characters.</span> | |
)} | |
<button>Submit</button> | |
</form> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment