fn

useFocus

v0.0.14testeddemo

Reactive focus state of an element. The returned focused ref tracks focus/blur events and can be written to in order to focus or blur the target.

Examples

ts
const el = useTemplateRef<HTMLInputElement>('el');
const { focused } = useFocus(el);
// focus the element imperatively
focused.value = true;
ts
// only treat keyboard focus as focused
const { focused } = useFocus(el, { focusVisible: true });

Demo

Loading demo…

Signature

ts
export function useFocus(
  target: MaybeComputedElementRef,
  options: UseFocusOptions ={ ... }

Parameters

ParameterTypeDescription
targetMaybeComputedElementRefThe element (or template ref) to track.
options?UseFocusOptionsOptions

Returns

UseFocusReturnAn object containing the writable focused ref.
PropertyTypeDescription
focusedWritableComputedRef<boolean>Reactive focus state. Read it to know whether the target is focused, or write to it to programmatically focus (true) or blur (false) the target.