UNPKG

rsuite

Version:

A suite of react components

58 lines (51 loc) 1.7 kB
'use client'; import { useRef, useCallback, useEffect } from 'react'; /** * A hook that manages the refs and focus behavior for a PIN input component */ export const usePinInputRefs = (length, autoFocus) => { // Create ref to store input elements const inputRefs = useRef([]); // Initialize the refs array when length changes useEffect(() => { inputRefs.current = inputRefs.current.slice(0, length); }, [length]); // Auto focus the first input on mount if autoFocus is true useEffect(() => { if (autoFocus && inputRefs.current[0]) { var _inputRefs$current$; (_inputRefs$current$ = inputRefs.current[0]) === null || _inputRefs$current$ === void 0 || _inputRefs$current$.focus(); } }, [autoFocus]); // Focus a specific input by index const focusInput = useCallback(index => { if (index >= 0 && index < length && inputRefs.current[index]) { var _inputRefs$current$in; (_inputRefs$current$in = inputRefs.current[index]) === null || _inputRefs$current$in === void 0 || _inputRefs$current$in.focus(); return true; } return false; }, [length]); // Focus the next input const focusNextInput = useCallback(currentIndex => { return focusInput(currentIndex + 1); }, [focusInput]); // Focus the previous input const focusPrevInput = useCallback(currentIndex => { return focusInput(currentIndex - 1); }, [focusInput]); // Get ref setter for an input const getRefSetter = useCallback(index => { return el => { inputRefs.current[index] = el; }; }, []); return { inputRefs, focusInput, focusNextInput, focusPrevInput, getRefSetter }; }; export default usePinInputRefs;