UNPKG

moq-ui

Version:

Simple, customizable UI components built with React

134 lines (106 loc) 3.24 kB
var React = require('react'); var RadioButton = require('./radio-button'); var RadioButtonGroup = React.createClass({ propTypes: { name: React.PropTypes.string.isRequired, valueSelected: React.PropTypes.string, defaultSelected: React.PropTypes.string, onChange: React.PropTypes.func }, _hasCheckAttribute: function(radioButton) { return radioButton.props.hasOwnProperty('checked') && radioButton.props.checked; }, getInitialState: function() { return { numberCheckedRadioButtons: 0, selected: this.props.valueSelected || this.props.defaultSelected || '' }; }, componentWillMount: function() { var cnt = 0; var selected = this.state.selected; this.props.children.forEach(function(option) { if (this._hasCheckAttribute(option)) { cnt++; selected = option.props.value; } }, this); this.setState({ numberCheckedRadioButtons: cnt, selected: selected }); }, componentWillReceiveProps: function(nextProps) { if (nextProps.hasOwnProperty('valueSelected')) { this.setState({selected: nextProps.valueSelected}); } }, getClasses: function() { var classString = 'moq-radio-button-group'; if (this.props.className && this.props.className.length) { classString += ' ' + this.props.className; } return classString; }, render: function() { var options = this.props.children.map(function(option) { if (option.type.displayName == 'RadioButton') { var { name, value, labelText, ...other } = option.props; return <RadioButton {...other} ref={option.props.value} name={this.props.name} key={option.props.value} value={option.props.value} labelText={option.props.labelText} onChange={this._onChange} checked={option.props.value == this.state.selected} /> } else { return option; } }, this); return ( <div className={this.getClasses()} onMouseDownCapture={this._onMouseDown}> {options} </div> ); }, _onMouseDown: function(e) { if (this.state.numberCheckedRadioButtons == 0) { if (this.props.onMouseDown) this.props.onMouseDown(e); } else { e.stopPropagation(); var message = "Cannot select a different radio button while another radio button " + "has the 'checked' property set to true."; console.error(message); } }, _updateRadioButtons: function(newValue) { if (this.state.numberCheckedRadioButtons == 0) { this.setState({selected: newValue}); } }, _onChange: function(e, newValue) { this._updateRadioButtons(newValue); // Successful update if (this.state.numberCheckedRadioButtons == 0) { if (this.props.onChange) this.props.onChange(e, newValue); } }, getSelectedValue: function() { return this.state.selected; }, setSelectedValue: function(newSelectionValue) { this._updateRadioButtons(newSelectionValue); }, clearValue: function() { this.setSelectedValue(''); } }); module.exports = RadioButtonGroup;