Back to Mantine

Use Focus Within

apps/mantine.dev/src/pages/hooks/use-focus-within.mdx

9.3.21.0 KB
Original Source

import { UseFocusWithinDemos } from '@docs/demos'; import { Layout } from '@/layout'; import { MDX_DATA } from '@/mdx';

export default Layout(MDX_DATA.useFocusWithin);

Usage

The use-focus-within hook detects if any element within another element has focus. It works the same way as the :focus-within CSS selector:

<Demo data={UseFocusWithinDemos.usage} />

Definition

tsx
interface UseFocusWithinOptions {
  onFocus?: (event: FocusEvent) => void;
  onBlur?: (event: FocusEvent) => void;
}

interface UseFocusWithinReturnValue<T extends HTMLElement = any> {
  ref: React.RefCallback<T | null>;
  focused: boolean;
}

function useFocusWithin<T extends HTMLElement = any>(
  options?: UseFocusWithinOptions,
): UseFocusWithinReturnValue<T>

Exported types

UseFocusWithinOptions and UseFocusWithinReturnValue types are exported from the @mantine/hooks package; you can import them in your application:

tsx
import type { UseFocusWithinOptions, UseFocusWithinReturnValue } from '@mantine/hooks';