Skip to content

useFocusWithin

Category
Export Size
479 B
Last Changed
5 days ago

Reactive utility to track if an element or one of its descendants has focus. It is meant to match the behavior of the :focus-within CSS pseudo-class. A common use case would be on a form element to see if any of its inputs currently have focus.

Demo

Basic Usage

tsx
import { 
useFocusWithin
} from '@reause/core'
import {
useRef
} from 'react'
const
target
=
useRef
<HTMLFormElement>(null)
const {
focused
} =
useFocusWithin
(
target
)
// `focused` is true while the form or any input inside it has focus

Type Declarations

ts
export interface UseFocusWithinReturn {
    focused: boolean;
}

export type ElementTarget<T extends TargetElement = TargetElement> = RefObject<T | null>

export type ElementTargetOrArray<T extends TargetElement = TargetElement> = ElementTarget<T> | ElementTarget<T>[]

export function useFocusWithin(target: ElementTarget, options?: ConfigurableWindow): UseFocusWithinReturn

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
bc99e - fix(core): resolve useFocusWithin audit findings (#575)
8fddc - chore!: remove all Vue-only Maybe* types and getter unions, adopt React Ref (#462)

Released under the MIT License. v0.1.8