UNPKG

@julo-ui/otp-input

Version:

React Input Component for entering sequences of digits

45 lines (43 loc) 1 kB
// src/usecase/use-handle-focus.ts import { useCallback, useEffect, useState } from "react"; function useHandleFocus(options) { const { autoFocus, manageFocus, descendants } = options; const [focusedIndex, setFocusedIndex] = useState(-1); const onFocusNext = useCallback( (index) => { if (!manageFocus) return; const next = descendants.next(index, false); if (next) requestAnimationFrame(() => { next.node.focus(); }); }, [descendants, manageFocus] ); const onFocus = useCallback((index) => { setFocusedIndex(index); }, []); const onBlur = useCallback(() => { setFocusedIndex(-1); }, []); useEffect(() => { if (autoFocus) { const first = descendants.first(); if (first) { requestAnimationFrame(() => { first.node.focus(); }); } } }, [descendants]); return { focusedIndex, onFocusNext, onFocus, onBlur }; } export { useHandleFocus };