Skip to content

Commit

Permalink
Add getInputArrayFromProps util, use it to initialize this.state.input
Browse files Browse the repository at this point in the history
also, add getValueFromProps util to handle props.forceUppercase and null | undefined
  • Loading branch information
acusti committed Jun 22, 2022
1 parent 724aa80 commit 6ed67e4
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 16 deletions.
18 changes: 3 additions & 15 deletions src/ReactCodeInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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();
Expand Down
13 changes: 12 additions & 1 deletion src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,15 @@ export const uuidv4 = () => {
let r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
};

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] || '');
};

0 comments on commit 6ed67e4

Please sign in to comment.