Watching form changes using react-hook-form
A super helpful react package I am working with is called react-hook-form. It allows you to easily build and validate forms. It is pretty useful. Here I focus on a feature called watch, which is usually not the first thing you would use when starting to use react-hook-form.
Watch
Watch allows you to observe form changes (🤯). It will notify you whenever an input changes. This way you don’t have to wait for the user to submit the form in order to do something.
import React from ‘react’;import { useForm } from “react-hook-form”;const UseFormWatchExample = () => { const { register, watch } = useForm(); const title = watch(‘title’) return ( <form> <input name=’title’ ref={register()}/> <h1>{title}</h1> </form> );};export default UseFormWatchExample
How Does it work
- First, we name our input “title” and register it to the form.
- We then watch input changes using the watch(“title”) statement.
- The title changes every time the user types a letter and then it is displayed inside the h1 tag
Watch API
You can use watch on a single form field (Like I showed in the example), an array of field names or to watch all fields by not passing any parameter to the function. Check out the official documentation for more details.
Liked my article? Looking for a job?
Check out my latest project: secrethunter.io