Skip to content

useFocusWithin

Reports whether focus is currently inside a subtree.

Reports whether focus is currently inside a subtree.

Import

import { useFocusWithin } from '@kamod-ch/hooks'

Live demo

Basic demo

Reports whether focus is currently inside a subtree.

Browser-only demo

This demo starts after the page mounts in the browser.
import { useRef } from 'preact/hooks'
import { useFocusWithin } from '@kamod-ch/hooks'

export default function UseFocusWithinDemo() {
  const ref = useRef<HTMLDivElement>(null)
  const focused = useFocusWithin(ref)

  return (
    <div>
      <div ref={ref} class="demo-target-box">
        <input placeholder="Focus me" />
        <button type="button">Focusable button</button>
      </div>
      <p><strong>Focus within:</strong> {String(focused)}</p>
    </div>
  )
}

API

TypeScript signature
import type { BasicTarget } from "../utils/domTarget.js";
export interface Options {
    onFocus?: (e: FocusEvent) => void;
    onBlur?: (e: FocusEvent) => void;
    onChange?: (isFocusWithin: boolean) => void;
}
export default function useFocusWithin(target: BasicTarget, options?: Options): boolean;
/

SSR considerations

This hook touches browser APIs. Render it after mount or guard it with BrowserOnly in SSR and static builds.

Browser compatibility

Requires the corresponding browser API to exist in the current environment.