Skip to content
Tier

useFocusWithin

Pro

Tracks whether focus is inside an element, for an item that moves focus when what the person was using goes or finishes. An item moves focus only when focus is inside it, or on its control that was removed, never because document.activeElement is body: a poll, a hold or a timer that finishes while the person is elsewhere, or nowhere, leaves focus alone (announce instead). A target held for the next render is dropped as soon as the person moves focus out, so it never pulls focus back later.

Focus leaves when it lands on an element outside, when the person presses outside, or when the element that had it blurs to nowhere and is still on the page; the window losing focus isn't leaving. Focus already inside when the item mounts (a control's autoFocus) counts as inside. Read inside() and held() in handlers and effects, not while rendering.

const focus = useFocusWithin<"heading" | "retry">(root)
// In the handler that removes what had focus:
if (focus.inside()) focus.hold("heading")
else announce(t("done"))
// In an effect, once the next render has drawn the target:
React.useEffect(() => {
  const target = focus.held()
  if (target === null) return
  focus.drop()
  ;({ heading: heading.current, retry: retry.current })[target]?.focus()
})
Markdown
Version 5.2.0· other versions

This page is for 5.2.0, the current release. An earlier release’s page is the Markdown that release published, so the docs match the version you have installed (candor-lock.json records it).

No earlier release’s docs have this page.

Not in the docs of 1.3.0, 1.4.0, 1.5.0, 1.5.1, 1.6.0, 1.7.0, 1.8.0, 1.8.1, 1.9.0, 1.9.1, 2.0.0, 2.1.0, 2.2.0, 2.3.0, 2.4.0, 2.5.0, 2.5.1, 2.6.0, 2.6.1, 2.6.2, 2.7.0, 2.8.0, 2.9.0, 2.10.0, 3.0.0, 4.0.0, 4.0.1, 4.0.2, 4.1.0, 4.2.0, 4.3.0, 4.4.0, 4.5.0, 5.0.0 and 5.1.0: the page came later, or had another name then.

Docs pages weren’t kept for 1.0.0, 1.0.1, 1.1.0, 1.1.1, 1.2.0 and 1.2.1: they are kept from 1.3.0 on, and before that only llms.txt was published.

Preview

It's types and helpers, listed below.

Install

With the Candor CLI

First time? Get started sets up the registry and theme. Or with shadcn directly: npx shadcn@latest add @candor/use-focus-within

Brings in: tokens

Functions

useFocusWithin(ref: React.RefObject<HTMLElement | null>)