diff --git a/src/ReactCodeInput.js b/src/ReactCodeInput.js index 0015455..84a6a2b 100644 --- a/src/ReactCodeInput.js +++ b/src/ReactCodeInput.js @@ -7,7 +7,7 @@ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; -import { uuidv4 } from './utils'; +import { getInputArrayFromProps, getValueFromProps, uuidv4 } from './utils'; const BACKSPACE_KEY = 8; const LEFT_ARROW_KEY = 37; @@ -32,23 +32,11 @@ class ReactCodeInput extends Component { constructor(props) { super(props); - const { fields, forceUppercase } = props; - let value = props.value || ''; - - if (forceUppercase) { - value = value.toUpperCase(); - } - this.state = { - value, - input: [], + input: getInputArrayFromProps(props), + value: getValueFromProps(props), }; - for (let i = 0; i < Number(fields) && i < 32; i += 1) { - const value = this.state.value[i] || ''; - this.state.input.push(value); - } - this.textInput = []; this.uuid = uuidv4(); diff --git a/src/utils.js b/src/utils.js index 858f207..c5aa727 100644 --- a/src/utils.js +++ b/src/utils.js @@ -3,4 +3,15 @@ export const uuidv4 = () => { let r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); -}; \ No newline at end of file +}; + +export const getValueFromProps = ({ forceUppercase, value }) => { + value = value == null ? '' : value; + return forceUppercase ? value.toUpperCase() : value; +}; + +export const getInputArrayFromProps = (props) => { + const fields = Math.min(32, props.fields); + const value = getValueFromProps(props); + return Array.from(Array(fields)).map((_, index) => value[index] || ''); +};