useFocusWithin
function useFocusWithin(ref: RefObject<Element | null>): boolean;
Returns whether focus is on the element or anywhere inside it, the same as CSS :focus-within,
and re-renders as focus moves in and out, by keyboard or by mouse.
- It is right from the first render when focus starts inside, for example on an
autoFocusfield. - It checks the ref's current element, so it follows the ref to a new element.
- It stays
truewhile focus moves between elements inside, so content rendered only while focused, like the suggestions below, stays open as Tab moves into it. - It is
falseduring server rendering.
For styling alone, CSS :focus-within is simpler. Use this when focus changes what renders,
such as showing a search box's suggestions only while you're in it.
Live demo
Example
import { useRef } from "react";
import { useFocusWithin } from "react-honey-hooks";
function SearchBox() {
const ref = useRef<HTMLDivElement>(null);
const focused = useFocusWithin(ref);
return (
<div ref={ref}>
<input type="search" aria-label="Search" />
{focused && <Suggestions />}
</div>
);
}