useFocusWithin

Respond to focus interactions that occur within the subtree of an element.

Listen to changes in the “focus” state of the element and its subtree. This hook is similar to the CSS :focus-within pseudo-class. Note that onBlurWithin and onFocusWithin are called each time the focus moves within the subtree, whereas onFocusWithinChange is only called once when focus enters and leaves the entire subtree.

import { useFocusWithin } from 'react-gui/use-focus-within';

const ref = useFocusWithin(focusWithinProps);

API #

Return value #

useFocusWithin returns a React callback ref.

ref (?HTMLElement) => void

A callback ref that must be passed to the target element.

FocusWithinProps #

disabled boolean

Disable the hook.

onBlurWithin (event: FocusEvent) => void

Called once the target AND all its descendants lose focus.

onFocusWithin (event: FocusEvent) => void

Called once the target OR one of its descendants receives focus.

onFocusWithinChange (focused: boolean) => void

Called each time the focus-within state changes

FocusEvent #

The W3C FocusEvent

relatedTarget boolean

The relatedTarget is the secondary target of the event. In some cases (such as when tabbing in or out a page), this property may be set to null for security reasons.


Examples #

Use onFocusWithinChange as a convenient way to listen to whether the focus is contained within the subtree.

import useFocusWithin from 'react-gui/use-focus-within';

function useFocusWithinState() {
const [isFocusWithin, onFocusWithinChange] = React.useState(false);
const ref = useFocusWithin({ onFocusWithinChange });
return [ref, isFocusWithin];
}
Updated
Edit
React GUICopyright © Facebook Inc.