Field: make id optional, generate one if not provided

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>
This commit is contained in:
Michael Telatynski 2020-03-29 22:59:15 +01:00
parent 7bdd22ae03
commit 19aae087e0
31 changed files with 36 additions and 57 deletions

View file

@ -23,9 +23,15 @@ import { debounce } from 'lodash';
// Invoke validation from user input (when typing, etc.) at most once every N ms.
const VALIDATION_THROTTLE_MS = 200;
const BASE_ID = "mx_Field";
let count = 1;
function getId() {
return `${BASE_ID}_${count++}`;
}
export default class Field extends React.PureComponent {
static propTypes = {
// The field's ID, which binds the input and label together.
// The field's ID, which binds the input and label together. Immutable.
id: PropTypes.string.isRequired,
// The element to create. Defaults to "input".
// To define options for a select, use <Field><option ... /></Field>
@ -70,6 +76,8 @@ export default class Field extends React.PureComponent {
feedback: undefined,
focused: false,
};
this.id = this.props.id || getId();
}
onFocus = (ev) => {
@ -167,6 +175,7 @@ export default class Field extends React.PureComponent {
inputProps.type = inputProps.type || "text";
inputProps.ref = input => this.input = input;
inputProps.placeholder = inputProps.placeholder || inputProps.label;
inputProps.id = this.id; // this overwrites the id from props
inputProps.onFocus = this.onFocus;
inputProps.onChange = this.onChange;
@ -211,7 +220,7 @@ export default class Field extends React.PureComponent {
return <div className={fieldClasses}>
{prefixContainer}
{fieldInput}
<label htmlFor={this.props.id}>{this.props.label}</label>
<label htmlFor={this.id}>{this.props.label}</label>
{postfixContainer}
{fieldTooltip}
</div>;