Skip to content

Commit 09cd315

Browse files
committed
Add getInputArray util and use it to initialize this.state.input
1 parent 9279d89 commit 09cd315

File tree

2 files changed

+10
-10
lines changed

2 files changed

+10
-10
lines changed

src/ReactCodeInput.js

+3-9
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import React, { Component } from 'react';
88
import PropTypes from 'prop-types';
99
import classNames from 'classnames';
10-
import { uuidv4 } from './utils';
10+
import { getInputArray, uuidv4 } from './utils';
1111

1212
const BACKSPACE_KEY = 8;
1313
const LEFT_ARROW_KEY = 37;
@@ -32,23 +32,17 @@ class ReactCodeInput extends Component {
3232
constructor(props) {
3333
super(props);
3434

35-
const { fields, forceUppercase } = props;
3635
let value = props.value || '';
3736

38-
if (forceUppercase) {
37+
if (props.forceUppercase) {
3938
value = value.toUpperCase();
4039
}
4140

4241
this.state = {
4342
value,
44-
input: [],
43+
input: getInputArray(props),
4544
};
4645

47-
for (let i = 0; i < Number(fields) && i < 32; i += 1) {
48-
const value = this.state.value[i] || '';
49-
this.state.input.push(value);
50-
}
51-
5246
this.textInput = [];
5347

5448
this.uuid = uuidv4();

src/utils.js

+7-1
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,10 @@ export const uuidv4 = () => {
33
let r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
44
return v.toString(16);
55
});
6-
};
6+
};
7+
8+
export const getInputArray = ({ fields, value }) => {
9+
fields = Math.min(32, fields);
10+
value = value || '';
11+
return Array.from(Array(fields)).map((_, index) => value[index] || '');
12+
};

0 commit comments

Comments
 (0)