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. |
- 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>)}
import { useEffect } from "react"import { useForm } from "react-hook-form"export default function App() {const { register, handleSubmit, setFocus } = useForm()const onSubmit = (data) => 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.
Troubleshooting
setFocus does nothing
Why it happens
React Hook Form can only focus a mounted field whose DOM ref was received through register or field.ref. A custom input that drops the ref, or a field that is not currently rendered, has no focusable element.
Fix
Forward the ref to the actual input. With Controller, pass field.ref to the component's ref prop (for example, inputRef), and call setFocus only after the field is mounted.
Focusing immediately after reset does not work
Why it happens
reset updates the form and its field references. In the same call stack, the target input may not have registered its ref again yet.
Fix
Focus after React has committed the reset, for example from an effect that runs when the reset state changes. Avoid calling reset() and setFocus() back-to-back.