# setFocus

> Programmatically focus any registered input field, with an option to also select its current value in React Hook Form.

Source: https://react-hook-form.com/docs/useform/setfocus

## `setFocus:` [UseFormSetFocus](https://react-hook-form.com/ts#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. |

> **Important: 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

---

**TS**

[Open in CodeSandbox](https://codesandbox.io/s/setfocus-rolus)

```tsx
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>
  )
}
```

**JS**

[Open in CodeSandbox](https://codesandbox.io/s/setfocus-rolus)

```javascript
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:

  ```javascript
  useEffect(() => {
    setFocus("firstName")
  }, [setFocus])
  ```

- You do not need `setFocus` to focus the first invalid field on submit. [`shouldFocusError`](https://react-hook-form.com/docs/useform#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](https://react-hook-form.com/docs/usecontroller).
