UNPKG

react-simple-otp

Version:
110 lines (100 loc) 3.17 kB
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var React = require('react'); var React__default = _interopDefault(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 = React.useState(new Array(length).fill('')), otp = _useState[0], setOtp = _useState[1]; var refs = []; otp.map(function (l, index) { refs[index] = React.useRef(null); }); var submitOnEnter = function submitOnEnter() { onSubmit(otp.join('')); }; React.useEffect(function () { if (!value) { setOtp(new Array(length).fill('')); refs[0].current.focus(); } }, [value]); React.useEffect(function () { onChange(otp.join('')); }, [otp]); return /*#__PURE__*/React__default.createElement("div", { style: { display: 'flex' } }, otp.map(function (otpField, index) { return /*#__PURE__*/React__default.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__default.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() {} }; module.exports = OTPField; //# sourceMappingURL=index.js.map