UNPKG

react-native-input-code-otp

Version:

react-native-input-code-otp is a high-performance and fully customizable OTP input component for React Native, inspired by @shadcn/ui.

86 lines (85 loc) 2.21 kB
"use strict"; import { createContext, useCallback, useContext, useMemo, useRef, useState } from 'react'; import { jsx as _jsx } from "react/jsx-runtime"; const TextInputOTPContext = /*#__PURE__*/createContext({ code: '', currentIndex: 0, inputRef: { current: null }, handleChangeText: () => {}, handlePress: () => {}, setValue: () => {}, focus: () => {}, blur: () => {}, clear: () => {}, caretHidden: false }); export function TextInputOTPProvider({ autoFocus = true, maxLength, value = '', onFilled, onChangeText, caretHidden = false, caretColor, children }) { const [code, setCode] = useState(value); const [currentIndex, setCurrentIndex] = useState(() => autoFocus ? 0 : -1); const inputRef = useRef(null); const handleChangeText = useCallback(text => { if (text.length > maxLength) { return; } setCode(text); onChangeText?.(text); if (text.length === maxLength) { onFilled?.(text); } if (text.length < maxLength) { setCurrentIndex(text.length); } }, [maxLength, onChangeText, onFilled]); const handlePress = useCallback(() => { setCurrentIndex(code.length); inputRef.current?.focus(); }, [code.length]); const setValue = useCallback(text => { const filledCode = text.length > maxLength ? text.slice(0, maxLength) : text; setCode(filledCode); setCurrentIndex(maxLength - 1); onFilled?.(filledCode); }, [maxLength]); function focus() { inputRef.current?.focus(); } function blur() { inputRef.current?.blur(); } const clear = useCallback(() => { setCode(''); setCurrentIndex(0); }, []); const contextValue = useMemo(() => ({ code: value || code, currentIndex, inputRef, handleChangeText, handlePress, setValue, focus, blur, clear, caretHidden, caretColor }), [clear, code, currentIndex, handleChangeText, handlePress, setValue, value, caretHidden, caretColor]); return /*#__PURE__*/_jsx(TextInputOTPContext.Provider, { value: contextValue, children: children }); } export function useTextInputOTP() { return useContext(TextInputOTPContext); } //# sourceMappingURL=use-text-input-otp.js.map