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.
91 lines (90 loc) • 2.44 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TextInputOTPProvider = TextInputOTPProvider;
exports.useTextInputOTP = useTextInputOTP;
var _react = require("react");
var _jsxRuntime = require("react/jsx-runtime");
const TextInputOTPContext = /*#__PURE__*/(0, _react.createContext)({
code: '',
currentIndex: 0,
inputRef: {
current: null
},
handleChangeText: () => {},
handlePress: () => {},
setValue: () => {},
focus: () => {},
blur: () => {},
clear: () => {},
caretHidden: false
});
function TextInputOTPProvider({
autoFocus = true,
maxLength,
value = '',
onFilled,
onChangeText,
caretHidden = false,
caretColor,
children
}) {
const [code, setCode] = (0, _react.useState)(value);
const [currentIndex, setCurrentIndex] = (0, _react.useState)(() => autoFocus ? 0 : -1);
const inputRef = (0, _react.useRef)(null);
const handleChangeText = (0, _react.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 = (0, _react.useCallback)(() => {
setCurrentIndex(code.length);
inputRef.current?.focus();
}, [code.length]);
const setValue = (0, _react.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 = (0, _react.useCallback)(() => {
setCode('');
setCurrentIndex(0);
}, []);
const contextValue = (0, _react.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__*/(0, _jsxRuntime.jsx)(TextInputOTPContext.Provider, {
value: contextValue,
children: children
});
}
function useTextInputOTP() {
return (0, _react.useContext)(TextInputOTPContext);
}
//# sourceMappingURL=use-text-input-otp.js.map