import React from 'react'; import { objEqual } from '../commons/utils'; export default class MaskedInput extends React.Component { constructor(props) { super(props); this.notifyChange = this.notifyChange.bind(this); // initialize an empty list of values this.state = {}; } componentWillMount() { const value = this.props.value !== undefined ? this.props.value : null; this.setState({ value: value }); } shouldComponentUpdate(nextProps, nextState) { return !objEqual(nextProps, this.props) || !objEqual(nextState, this.state); } /** * Notify the parent about change in the selection * @param {[type]} value The new value selected * @param {[type]} evt The control event, generated by react */ notifyChange(value, evt) { if (this.getValue() === value) { this._value = null; this.setState({ value: null }); } else { this._value = value; this.setState({ value: value }); } if (this.props.onChange) { this.props.onChange(evt, this.getValue()); } } /** * API exposed to the client to get its selected value. * It is not in the state because when the event is generated, the state is not immediatelly * updated * @return {Array|Object} An array, if it is a multi-selection or the item selected in the option list */ getValue() { return this._value; } /** * Return the rendered component for the label * @return {React.Component} The label component, or null if there is no label */ labelRender() { const label = this.props.label; return label ? React.createElement( 'label', { className: 'control-label' }, label ) : null; } /** * Component rendering * @return {React.Component} Component to display */ render() { const helpBlock = this.props.help ? React.createElement( 'div', { className: 'help-block' }, this.props.help ) : null; const clazz = 'form-group list-box' + (this.props.bsStyle ? ' has-' + this.props.bsStyle : ''); return React.createElement( 'div', { className: clazz }, this.labelRender(), React.createElement('input', { type: 'text', className: 'form-control' }), helpBlock ); } } MaskedInput.propTypes = { label: React.PropTypes.node, onChange: React.PropTypes.func, value: React.PropTypes.any, bsStyle: React.PropTypes.oneOf(['success', 'warning', 'error']), help: React.PropTypes.string };