use-focus-within

Detects if any element within other element has focus

Import

Usage

use-focus-within hook detects if any element within the other element 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}>
      <Box
        p="xl"
        style={{
          backgroundColor: focused ? 'var(--mantine-color-blue-light)' : 'transparent',
        }}
      >
        <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;
};