react-simple-otp
Version:
React OTP input
107 lines (98 loc) • 3 kB
JavaScript
import React, { useState, useRef, useEffect } from 'react';
var OTPField = function OTPField(_ref) {
var value = _ref.value,
inputStyle = _ref.inputStyle,
length = _ref.length,
onSubmit = _ref.onSubmit,
enableClearAll = _ref.enableClearAll,
autoFocus = _ref.autoFocus,
clearAllButton = _ref.clearAllButton,
clearAllButtonStyle = _ref.clearAllButtonStyle,
inputFieldClassName = _ref.inputFieldClassName,
clearAllButtonClassName = _ref.clearAllButtonClassName,
onChange = _ref.onChange;
var _useState = useState(new Array(length).fill('')),
otp = _useState[0],
setOtp = _useState[1];
var refs = [];
otp.map(function (l, index) {
refs[index] = useRef(null);
});
var submitOnEnter = function submitOnEnter() {
onSubmit(otp.join(''));
};
useEffect(function () {
if (!value) {
setOtp(new Array(length).fill(''));
refs[0].current.focus();
}
}, [value]);
useEffect(function () {
onChange(otp.join(''));
}, [otp]);
return /*#__PURE__*/React.createElement("div", {
style: {
display: 'flex'
}
}, otp.map(function (otpField, index) {
return /*#__PURE__*/React.createElement("input", {
key: index,
className: inputFieldClassName,
ref: refs[index],
style: inputStyle,
maxLength: 1,
autoFocus: index === 0 && autoFocus ? true : false,
value: otp[index],
onKeyDown: function onKeyDown(evt) {
if (evt.keyCode === 8) {
evt.preventDefault();
var newOtp = [].concat(otp);
var doesValueExist = newOtp[index];
newOtp[index] = '';
index - 1 >= 0 && !doesValueExist && refs[index - 1].current.focus();
if (index - 1 >= 0 && !doesValueExist) newOtp[index - 1] = '';
setOtp(newOtp);
}
if (index + 1 === length && evt.keyCode === 13) {
submitOnEnter();
}
},
onChange: function onChange(evt) {
var newOtp = [].concat(otp);
newOtp[index] = evt.target.value;
setOtp(newOtp);
evt.target.value !== '' && index + 1 < length && refs[index + 1].current.focus();
}
});
}), enableClearAll && /*#__PURE__*/React.createElement("button", {
style: clearAllButtonStyle,
className: clearAllButtonClassName,
onClick: function onClick() {
var newOtp = new Array(length).fill('');
setOtp(newOtp);
refs[0].current.focus();
}
}, clearAllButton));
};
OTPField.defaultProps = {
value: '',
inputStyle: {
outline: 'none',
textAlign: 'center',
width: '2rem',
height: '30px',
fontSize: '20px'
},
inputFieldClassName: '',
onSubmit: function onSubmit() {},
enableClearAll: false,
autoFocus: true,
clearAllButton: 'Clear',
clearAllButtonStyle: {
cursor: 'pointer'
},
clearAllButtonClassName: '',
onChange: function onChange() {}
};
export default OTPField;
//# sourceMappingURL=index.modern.js.map