Skip to content

setFocus

Manually set an input focus

setFocus: (name: string, options: SetFocusOptions) => void

This method will allow users to programmatically focus on input. Make sure input's ref is registered into the hook form.

Props


NameTypeDescription
namestringA input field name to focus
optionsshouldSelectbooleanWhether 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 * as React 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)
renderCount++
React.useEffect(() => {
setFocus("firstName")
}, [setFocus])
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName")} placeholder="First Name" />
<input type="submit" />
</form>
)
}
import * as React from "react"
import { useForm } from "react-hook-form"
export default function App() {
const { register, handleSubmit, setFocus } = useForm()
const onSubmit = (data) => console.log(data)
renderCount++
React.useEffect(() => {
setFocus("firstName")
}, [setFocus])
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName")} placeholder="First Name" />
<input type="submit" />
</form>
)
}

Thank you for your support

If you find React Hook Form to be useful in your project, please consider to star and support it.