Skip to main content

useFocus

A custom hook that returns the focus state of a target element and allows defining actions based on the focus state.


Code

🔗 View source 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

NameTypeDefaultDescription
onFocus(event: FocusEvent) => void-Callback invoked when the element receives focus
onBlur(event: FocusEvent) => void-Callback invoked when the element loses focus

Returns

NameTypeDescription
refReact.RefObject<T | null>Ref to attach to the target element
isFocusbooleanWhether the target element is currently focused
setFocus() => voidFunction 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