Skip to content

Commit

Permalink
update OTPInput.jsx
Browse files Browse the repository at this point in the history
  • Loading branch information
shivishbrahma committed Jul 27, 2024
1 parent afb5582 commit 829a694
Showing 1 changed file with 28 additions and 18 deletions.
46 changes: 28 additions & 18 deletions src/OTPInput/OTPInput.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import PropTypes from "prop-types";

import "./OTPInput.css";

function OTPInput({ length, ...otherProps }) {
const [otp, setOtp] = React.useState(Array(length).fill(""));
function OTPInput({ length,pattern, ...otherProps }) {
const [otp, setOtp] = React.useState("");

const inputs = [];

const handleChange = (element, index) => {
const value = element.value;
if (/\D/.test(value)) return; // Only allow digits
if (!pattern.test(value)) return; // Only allow digits

let newOtp = [...otp];
newOtp[index] = value;
Expand Down Expand Up @@ -43,39 +43,49 @@ function OTPInput({ length, ...otherProps }) {
const handlePaste = (e) => {
e.preventDefault();
const paste = e.clipboardData.getData("text");
if (/[^0-9]/.test(paste)) return; // Only allow digits
if (!pattern.test(paste)) return; // Only allow digits

const newOtp = paste.slice(0, length).split("");
for (let i = 0; i < length; i++) {
inputs[i].value = newOtp[i] || "";

if (newOtp[i] && i < length - 1) {
inputs[i + 1].focus();
}
}
setOtp(newOtp);
};

return (
<div className="OTPInput" {...otherProps} onPaste={handlePaste}>
{otp.map((_, index) => (
<input
className="OTPInput__input"
key={index}
type="text"
maxLength="1"
value={otp[index]}
onChange={(e) => handleChange(e.target, index)}
onKeyDown={(e) => handleKeyDown(e, index)}
ref={(input) => (inputs[index] = input)}
/>
))}
{Array(length)
.fill()
.map((_, i) => i + 1)
.map((_, index) => (
<input
className="OTPInput__input"
key={index}
type="text"
maxLength="1"
value={otp[index]?.toString() || ""}
onChange={(e) => handleChange(e.target, index)}
onKeyDown={(e) => handleKeyDown(e, index)}
placeholder="0"
ref={(input) => (inputs[index] = input)}
/>
))}
</div>
);
}

OTPInput.propTypes = {
length: PropTypes.number
length: PropTypes.number,
pattern: PropTypes.instanceOf(RegExp),
};

OTPInput.defaultProps = {
length: 6
length: 6,
pattern: /\d/
};

export default OTPInput;

0 comments on commit 829a694

Please sign in to comment.