v6.0.35

use-focus-within

Detect if any element within has focus
Import

Usage

use-focus-within hook detects if any element within has focus, it works the same way as :focus-within CSS selector:

One of elements has focus: false
import { useFocusWithin } from '@asuikit/hooks';
import { TextInput, Button, Box, Text } from '@asuikit/core';
function Demo() {
const { ref, focused } = useFocusWithin();
return (
<div ref={ref}>
<Box
sx={(theme) => ({
backgroundColor: focused
? theme.fn.variant({ variant: 'light' }).background
: 'transparent',
padding: theme.spacing.xl,
})}
>
<Text size="sm">One of elements has focus: {focused.toString()}</Text>
<TextInput label="Focus this input" placeholder="Styles will be added to parent" />
<Button mt="md">Button</Button>
</Box>
</div>
);
}

Definition

function useFocusWithin<T extends HTMLElement = any>(handlers?: {
onFocus?(event: FocusEvent): void;
onBlur?(event: FocusEvent): void;
}): {
ref: React.MutableRefObject<T>;
focused: boolean;
};