wix-style-react
Version:
wix-style-react
73 lines • 3.06 kB
JavaScript
import React from 'react';
import PropTypes from 'prop-types';
import Text from '../Text';
import { st, classes } from './LabelledElement.st.css';
import DataHooks from './dataHooks';
import { generateID } from '../utils/generateId';
class LabelledElement extends React.Component {
constructor() {
super(...arguments);
this.state = {
hasFocus: false,
inputId: `labelled-element-${generateID()}`,
value: undefined,
};
this._isInputEmpty = () => {
return this._isInputControlled() ? !this.props.value : !this.state.value;
};
this._isInputControlled = () => typeof this.props.value !== 'undefined';
this._handleFocus = event => {
this.setState({ hasFocus: true });
};
this._handleBlur = event => {
this.setState({
hasFocus: false,
});
};
this._handleOnChange = event => {
if (!this._isInputControlled()) {
this.setState({
value: event.target.value,
});
}
};
this._placeLabelOnTop = () => this.state.hasFocus || !this._isInputEmpty();
this._getPlaceholder = placeholder => (this._placeLabelOnTop() ? placeholder : '');
}
render() {
const { inputId } = this.state;
const { dataHook, label, children, disabled } = this.props;
const labelTop = this._placeLabelOnTop();
return (React.createElement("div", { className: classes.root, "data-hook": dataHook },
React.createElement("label", { "data-hook": DataHooks.label, "data-top": labelTop, htmlFor: inputId, className: st(classes.label, {
labelTop,
topLabelGray: this.props.topLabelGray,
disabled,
}) },
React.createElement(Text, { size: "medium", light: !labelTop, secondary: !labelTop, weight: "thin", className: classes.labelText }, label)),
children && (React.createElement("div", { "data-hook": DataHooks.childrenWrapper }, children({
id: inputId,
onFocus: this._handleFocus,
onBlur: this._handleBlur,
onChange: this._handleOnChange,
/** should have a different height than regular large input */
className: classes.inputContainer,
getPlaceholder: placeholder => this._getPlaceholder(placeholder),
})))));
}
}
LabelledElement.displayName = 'LabelledElement';
LabelledElement.propTypes = {
/** Specifies a data-hook for tests */
dataHook: PropTypes.string,
/** Sets the field label. */
label: PropTypes.string,
/** Specifies the value of rendered child input. */
value: PropTypes.string,
/** Specifies the top label color */
topLabelGray: PropTypes.bool,
/** Specifies if the field is disabled */
disabled: PropTypes.bool,
};
export default LabelledElement;
//# sourceMappingURL=LabelledElement.js.map