fleet/frontend/components/forms/fields/InputField/InputField.jsx

121 lines
2.9 KiB
React
Raw Normal View History

import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import { noop, pick } from 'lodash';
2016-12-16 15:54:49 +00:00
import FormField from 'components/forms/FormField';
const baseClass = 'input-field';
class InputField extends Component {
static propTypes = {
autofocus: PropTypes.bool,
2017-01-13 23:27:58 +00:00
disabled: PropTypes.bool,
error: PropTypes.string,
inputClassName: PropTypes.string, // eslint-disable-line react/forbid-prop-types
inputWrapperClass: PropTypes.string,
inputOptions: PropTypes.object, // eslint-disable-line react/forbid-prop-types
name: PropTypes.string,
onChange: PropTypes.func,
onFocus: PropTypes.func,
placeholder: PropTypes.string,
type: PropTypes.string,
2017-01-13 23:27:58 +00:00
value: PropTypes.oneOfType(
[PropTypes.bool, PropTypes.string, PropTypes.number]
).isRequired,
};
static defaultProps = {
autofocus: false,
inputWrapperClass: '',
inputOptions: {},
label: null,
labelClassName: '',
onFocus: noop,
type: 'text',
value: '',
};
componentDidMount () {
const { autofocus } = this.props;
const { input } = this;
if (autofocus) {
input.focus();
}
return false;
}
onInputChange = (evt) => {
evt.preventDefault();
const { value } = evt.target;
const { onChange } = this.props;
return onChange(value);
}
render () {
const {
2017-01-13 23:27:58 +00:00
disabled,
error,
inputClassName,
inputOptions,
inputWrapperClass,
name,
onFocus,
placeholder,
type,
value,
} = this.props;
2016-12-16 15:54:49 +00:00
const { onInputChange } = this;
const shouldShowPasswordClass = type === 'password';
2016-11-09 14:00:40 +00:00
const inputClasses = classnames(baseClass, inputClassName, {
[`${baseClass}--password`]: shouldShowPasswordClass,
2017-01-13 23:27:58 +00:00
[`${baseClass}--disabled`]: disabled,
2016-11-09 14:00:40 +00:00
[`${baseClass}--error`]: error,
[`${baseClass}__textarea`]: type === 'textarea',
});
2016-12-16 15:54:49 +00:00
const formFieldProps = pick(this.props, ['hint', 'label', 'error', 'name']);
if (type === 'textarea') {
return (
2016-12-16 15:54:49 +00:00
<FormField {...formFieldProps} type="textarea" className={inputWrapperClass}>
<textarea
name={name}
onChange={onInputChange}
className={inputClasses}
2017-01-13 23:27:58 +00:00
disabled={disabled}
placeholder={placeholder}
ref={(r) => { this.input = r; }}
type={type}
{...inputOptions}
value={value}
/>
2016-12-16 15:54:49 +00:00
</FormField>
);
}
return (
2016-12-16 15:54:49 +00:00
<FormField {...formFieldProps} type="input" className={inputWrapperClass}>
<input
2017-01-13 23:27:58 +00:00
disabled={disabled}
name={name}
onChange={onInputChange}
onFocus={onFocus}
className={inputClasses}
placeholder={placeholder}
ref={(r) => { this.input = r; }}
type={type}
{...inputOptions}
value={value}
/>
2016-12-16 15:54:49 +00:00
</FormField>
);
}
}
export default InputField;