Piplup
@piplup/rhf-coreHooks

useFormSetFocus

Returns a setFocus function for focusing registered fields from form context or a provided control.

useFormSetFocus returns a setFocus function for moving focus to a registered field. It is useful when buttons, error summaries, or other nested components need to focus a form field without receiving the full form instance as a prop.

If you do not pass a control, the hook reads it from form context, which makes it easy to use inside FormContainer or FormProvider.

Import

import { useFormSetFocus } from "@piplup/rhf-core";

Usage

"use client";import { useForm, type Control } from "react-hook-form";import { useFormSetFocus } from "@piplup/rhf-core";type FieldValues = {  email: string;  password: string;};function FocusEmailButton({ control }: { control?: Control<FieldValues> }) {  const setFocus = useFormSetFocus({ control });  return (    <button      type="button"      onClick={() => setFocus("email", { shouldSelect: true })}      className="border border-black hover:border-black/90 px-4 py-1 rounded"    >      Focus email    </button>  );}export default function Page() {  const { control, register, handleSubmit } = useForm({    defaultValues: {      email: "",      password: "",    },  });  return (    <form      onSubmit={handleSubmit((values) =>        alert(JSON.stringify(values, null, 2)),      )}      noValidate    >      <div>        <label htmlFor="email">Email</label>        <input          id="email"          type="email"          className="border rounded block px-2"          {...register("email")}        />      </div>      <div style={{ marginTop: 12 }}>        <label htmlFor="password">Password</label>        <input          id="password"          type="password"          className="border rounded block px-2"          {...register("password")}        />      </div>      <div style={{ display: "flex", gap: 8, marginTop: 12 }}>        <button          type="submit"          className="bg-black hover:bg-black/90 px-4 py-1 text-white rounded"        >          Submit        </button>        <FocusEmailButton control={control} />      </div>    </form>  );}

Props

Prop

Type

Return value

Prop

Type

Notes

  • Use this hook when nested components need focus control.
  • The returned function mirrors the familiar react-hookf-form setFocus API, including support for shouldSelect.
  • The field must be registered and backed by a focusable element for focus to succeed.

See also

On this page