otp-gen-ui
Version:
Generate OTP and render customizable input boxes for React
80 lines (77 loc) • 2.45 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
// src/generateOtp.ts
var generateOtp = (length = 6) => {
if (length <= 0 || !Number.isInteger(length)) {
throw new Error("OTP length must be a positive integer");
}
return Array.from({ length }, () => Math.floor(Math.random() * 10)).join("");
};
// src/OtpBox.tsx
import React, { useRef } from "react";
import { jsx } from "react/jsx-runtime";
var OtpBox = ({
length = 6,
onChange,
style,
inputStyle
}) => {
const [otp, setOtp] = React.useState(Array(length).fill(""));
const inputsRef = useRef([]);
const handleChange = (value, index) => {
var _a;
const newOtp = [...otp];
newOtp[index] = value.slice(-1);
setOtp(newOtp);
onChange == null ? void 0 : onChange(newOtp.join(""));
if (value && index < length - 1) {
(_a = inputsRef.current[index + 1]) == null ? void 0 : _a.focus();
}
};
const handleKeyDown = (e, index) => {
var _a;
if (e.key === "Backspace" && !otp[index] && index > 0) {
(_a = inputsRef.current[index - 1]) == null ? void 0 : _a.focus();
}
};
return /* @__PURE__ */ jsx("div", { style: __spreadValues({ display: "flex", gap: "8px" }, style), children: Array.from({ length }).map((_, i) => /* @__PURE__ */ jsx(
"input",
{
ref: (el) => {
inputsRef.current[i] = el;
},
value: otp[i],
onChange: (e) => handleChange(e.target.value, i),
onKeyDown: (e) => handleKeyDown(e, i),
maxLength: 1,
style: __spreadValues({
width: "40px",
height: "40px",
textAlign: "center",
fontSize: "18px",
border: "1px solid #ccc",
borderRadius: "5px"
}, inputStyle)
},
i
)) });
};
var OtpBox_default = OtpBox;
export {
OtpBox_default as OtpBox,
generateOtp
};