File size: 1,907 Bytes
1e92f2d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | import clsx from 'clsx';
import PropTypes from 'prop-types';
import { PureComponent } from 'react';
import './style.scss';
export default class FormTextInput extends PureComponent {
static propTypes = {
isError: PropTypes.bool,
isValid: PropTypes.bool,
selectOnFocus: PropTypes.bool,
className: PropTypes.string,
name: PropTypes.string,
value: PropTypes.any,
placeholder: PropTypes.any,
onChange: PropTypes.func,
hasCoreStyles: PropTypes.bool,
};
state = {
value: this.props.value || '',
};
currentTextField = undefined;
componentDidUpdate( oldProps ) {
this.updateValueIfNeeded( oldProps.value );
}
updateValueIfNeeded( oldValue ) {
const { value } = this.props;
if ( oldValue !== value || value !== this.state.value ) {
this.setState( { value } );
}
}
textFieldRef = ( element ) => {
this.currentTextField = element;
const { inputRef } = this.props;
if ( ! inputRef ) {
return;
}
if ( typeof inputRef === 'function' ) {
inputRef( element );
} else {
inputRef.current = element;
}
};
focus() {
if ( this.currentTextField ) {
this.currentTextField.focus();
}
}
selectOnFocus = ( event ) => {
if ( this.props.selectOnFocus ) {
event.target.select();
}
};
onChange = ( event ) => {
this.setState( { value: event.target.value } );
this.props.onChange?.( event );
};
render() {
const { isError, isValid, hasCoreStyles, selectOnFocus, inputRef, onChange, value, ...rest } =
this.props;
const classes = clsx( 'form-text-input', this.props.className, {
'is-error': this.props.isError,
'is-valid': this.props.isValid,
'form-text-input-core-styles': hasCoreStyles,
} );
return (
<input
type="text"
{ ...rest }
value={ this.state.value }
ref={ this.textFieldRef }
className={ classes }
onClick={ this.selectOnFocus }
onChange={ this.onChange }
/>
);
}
}
|