Skip to content

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


NameTypeDescription
namestringAn input field name to focus
optionsshouldSelectbooleanSince 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 ref during register.
  • Avoid calling setFocus right after reset as all input references will be removed by reset API.

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 setFocus to focus the first invalid field on submit. shouldFocusError does this by default.

  • For a component that does not forward a DOM ref, give field.ref an object with a focus method. 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.