setFocus
Programmatically focus a registered input field.
</> setFocus: UseFormSetFocus
This method will allow users to programmatically focus on input. Make sure input's ref is registered into the hook form.
Props
| Name | Type | Description | |
|---|---|---|---|
name | string | An input field name to focus | |
options | shouldSelect | boolean | Since v7.27.0 Whether to select the input content on focus. |
RULES
- This API will invoke focus method from the ref, so it's important to provide
refduringregister. - Avoid calling
setFocusright afterresetas all input references will be removed byresetAPI.
Examples
import { useEffect } from "react"import { useForm } from "react-hook-form"type FormValues = {firstName: string}export default function App() {const { register, handleSubmit, setFocus } = useForm<FormValues>()const onSubmit = (data: FormValues) => console.log(data)useEffect(() => {setFocus("firstName")}, [setFocus])return (<form onSubmit={handleSubmit(onSubmit)}><input {...register("firstName")} placeholder="First Name" /><input type="submit" /></form>)}
Tips
-
Focus the first field when the form opens:
useEffect(() => {setFocus("firstName")}, [setFocus]) -
You do not need
setFocusto focus the first invalid field on submit.shouldFocusErrordoes this by default. -
For a component that does not forward a DOM ref, give
field.refan object with afocusmethod. See the Tips section of useController.