How to Modify other Form Fields using React Hook Form watch & setValue
React hook form's useWatch is a great way to get the data from the form. But it cannot easily update other form fields based on the watch field. In this article, we will show you how to modify other form fields using React Hook Form's useWatch
The Problem
Imagine you have a contact form with a name field and a subject field. Now, you want to change the subject based on the user input in the name field. Here is how you can do it with react hook form and watch.
The Solution
First import react-hook-form
:
import { useForm } from "react-hook-form";
Then, create a form with the useForm
hook and import the watch
prop & setValue
prop as well.
const { register, handleSubmit, watch, setValue } = useForm();
Then we need to watch the name field and update the subject field based on the user input. For that we have to use the watch
prop and setValue
prop.
// watch "name" field and set default value to "Someone"
const watchName = watch("name", "Someone")
// set value to "subject" based on the watch field
React.useEffect(() => {
setValue("subject", `${watchName} sent a message from Web3Forms`)
}, [userName]);
Now, create a <form>
tag and add the onSubmit
prop.
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("name")} />
<input type="hidden" {...register("subject")} />
<button type="submit">Submit</button>
</form>
That's it. Now, the subject field will be updated based on the user input in the name field. You can also use the React Hook Form documentation to learn more.
Here's the full code for reference:
import { useForm } from "react-hook-form";
function App() {
const { register, handleSubmit, watch, setValue } = useForm();
const watchName = watch("name", "Someone")
React.useEffect(() => {
setValue("subject", `${watchName} sent a message from Web3Forms`)
}, [watchName]);
const onSubmit = async (data, e) => {
console.log(data);
// use a contact form API to send the data to your server
// try: web3forms.com
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("name")} />
<input type="hidden" {...register("subject")} />
<button type="submit">Submit</button>
</form>
);
}
Wrapping Up
That's it, React hook form is easier to work with. But you can also do more with Web3Forms like sending the form submissions directly to your email. Please create an access key from Web3Forms to get started.