Skip to content

Commit 33a7aca

Browse files
committed
Add getInputArrayFromProps util, use it to initialize this.state.input
also, add getValueFromProps util to handle props.forceUppercase and null | undefined
1 parent 9279d89 commit 33a7aca

File tree

2 files changed

+15
-16
lines changed

2 files changed

+15
-16
lines changed

src/ReactCodeInput.js

+3-15
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 { getInputArrayFromProps, getValueFromProps, uuidv4 } from './utils';
1111

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

35-
const { fields, forceUppercase } = props;
36-
let value = props.value || '';
37-
38-
if (forceUppercase) {
39-
value = value.toUpperCase();
40-
}
41-
4235
this.state = {
43-
value,
44-
input: [],
36+
input: getInputArrayFromProps(props),
37+
value: getValueFromProps(props),
4538
};
4639

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-
5240
this.textInput = [];
5341

5442
this.uuid = uuidv4();

src/utils.js

+12-1
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,15 @@ 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 getValueFromProps = ({ forceUppercase, value }) => {
9+
value = value == null ? '' : value;
10+
return forceUppercase ? value.toUpperCase() : value;
11+
};
12+
13+
export const getInputArrayFromProps = (props) => {
14+
const fields = Math.min(32, props.fields);
15+
const value = getValueFromProps(props);
16+
return Array.from(Array(fields)).map((_, index) => value[index] || '');
17+
};

0 commit comments

Comments
 (0)