useFocus
A custom hook that returns the focus state of a target element and allows defining actions based on the focus state.
Code
Interface
typescript
interface UseFocusProps {
onFocus?: (event: FocusEvent) => void;
onBlur?: (event: FocusEvent) => void;
}
interface UseFocusReturnType<T extends HTMLElement> {
ref: React.RefObject<T | null>;
isFocus: boolean;
setFocus: () => void;
}
function useFocus<T extends HTMLElement>({
onFocus,
onBlur,
}: UseFocusProps = {}): UseFocusReturnType<T>
Options
| Name | Type | Default | Description |
|---|---|---|---|
onFocus | (event: FocusEvent) => void | - | Callback invoked when the element receives focus |
onBlur | (event: FocusEvent) => void | - | Callback invoked when the element loses focus |
Returns
| Name | Type | Description |
|---|---|---|
ref | React.RefObject<T | null> | Ref to attach to the target element |
isFocus | boolean | Whether the target element is currently focused |
setFocus | () => void | Function to programmatically focus the target element |
Usage
typescript
import { useFocus } from '@modern-kit/react';
const Example = () => {
const { ref, isFocus, setFocus } = useFocus<HTMLInputElement>({
onFocus: () => console.log("focus"),
onBlur: () => console.log("blur"),
});
return (
<div>
<input ref={ref} />
<button onClick={() => setFocus()}>focus trigger</button>
<div>{isFocus ? 'Focus' : 'Blur'}</div>
</div>
)
};
Example
Status: Blur