Skip to content

useFocus ​

Hook that allows you to focus on a specific element

browser
test coverage
Last changed: last month

Installation ​

Library
CLI
Manual
typescript
import { useFocus } from '@siberiacancode/reactuse';

Usage ​

typescript
const { focus, blur, focused } = useFocus(ref);
// or
const { ref, focus, blur, focused } = useFocus();

Demo ​

Api ​

Parameters

NameTypeDefaultNote
targetHookTarget-The target element to focus
options.initialValue?booleanfalseThe initial focus state of the target
options.onFocus?(event: FocusEvent) => void-The callback function to be invoked on focus
options.onBlur?(event: FocusEvent) => void-The callback function to be invoked on blur

Returns

UseFocusReturn

Parameters

NameTypeDefaultNote
options.initialValue?booleanfalseThe initial focus state of the target
options.onFocus?(event: FocusEvent) => void-The callback function to be invoked on focus
options.onBlur?(event: FocusEvent) => void-The callback function to be invoked on blur

Returns

UseFocusReturn & { ref: StateRef<Target> }

Type declaration ​

typescript
import type { HookTarget } from '@/utils/helpers';

import type { StateRef } from '../useRefState/useRefState';

export interface UseFocusOptions {
  /** The initial focus state of the target */
  initialValue?: boolean;
  /** The on blur callback */
  onBlur?: (event: FocusEvent) => void;
  /** The on focus callback */
  onFocus?: (event: FocusEvent) => void;
}

export interface UseFocusReturn {
  /** The boolean state value of the target */
  focused: boolean;
  /** Blur the target */
  blur: () => void;
  /** Focus the target */
  focus: () => void;
}

export interface UseFocus {
  (target: HookTarget, options?: UseFocusOptions): UseFocusReturn;

  <Target extends Element>(
    options?: UseFocusOptions,
    target?: never
  ): UseFocusReturn & { ref: StateRef<Target> };
}

Source ​

Source • Demo

Contributors ​

D
debabin
debabin

Released under the MIT License.