Detect if any element within has focus


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 '@mantine/hooks';
import { TextInput, Button, Box, Text } from '@mantine/core';
function Demo() {
const { ref, focused } = useFocusWithin();
return (
<div ref={ref}>
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>


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