Skip to main content

useFocus

The useFocus hook tells you whether an element has focus. Attach the returned ref to the element; with the within option it also reports focus on any descendant, which behaves like the CSS :focus-within selector.

Usage​

Installation​

import { useFocus } from "hookstorm";

Parameters​

  • options — (optional) An object with:
    • within — When true, the element counts as focused while any of its children has focus. Default: false.

Return Values​

  • ref — A ref to attach to the target element.
  • isFocused — true while the element (or a descendant, with within) has focus.

Example Usage​

import { ReactElement, RefObject } from "react";
import { useFocus } from "hookstorm";

export default function SearchBox(): ReactElement {
const { ref, isFocused } = useFocus({ within: true });

return (
<form
ref={ref as RefObject<HTMLFormElement>}
style={{ outline: isFocused ? "2px solid dodgerblue" : "none" }}
>
<input placeholder="Search..." />
<button type="submit">Go</button>
</form>
);
}

Notes​

  • Without within, the element itself must be focusable (for example an input, or any element with tabIndex).
  • The initial focus state is read when the hook mounts, so an element that was auto-focused is reported correctly.