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.
- within — When
Return Values
- ref — A ref to attach to the target element.
- isFocused —
truewhile the element (or a descendant, withwithin) 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 aninput, or any element withtabIndex). - The initial focus state is read when the hook mounts, so an element that was auto-focused is reported correctly.