Event Handling
useFocus
Returns whether a given element has focus and provides focus/blur methods.
About
Handles focus events for the immediate target element.
Examples
Track focus on a single input
import { useState } from "react";
import { useFocus } from "rooks";
export default function App() {
const [isFocused, setIsFocused] = useState(false);
const { focusProps } = useFocus<HTMLInputElement>({
onFocusChange: setIsFocused,
});
return (
<label style={{ display: "block" }}>
Name:
<input
{...focusProps}
style={{
border: isFocused ? "3px solid orange" : "1px solid gray",
}}
/>
</label>
);
}Ignore focus from nested children
import { useState } from "react";
import { useFocus } from "rooks";
export default function App() {
const [message, setMessage] = useState("Container is idle");
const { focusProps } = useFocus<HTMLDivElement>({
onFocus: () => setMessage("Container focused directly"),
onBlur: () => setMessage("Container blurred"),
});
return (
<div>
<div
{...focusProps}
tabIndex={0}
style={{ padding: 12, border: "1px solid #999" }}
>
Focus this container directly
<button type="button">Nested button</button>
</div>
<p>{message}</p>
</div>
);
}