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.
A callback ref that must be passed to the target element.
FocusWithinProps #
Disable the hook.
Called once the target AND all its descendants lose focus.
Called once the target OR one of its descendants receives focus.
Called each time the focus-within state changes
FocusEvent #
The W3C FocusEvent
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];
}