|
| 1 | +import React, { Component, PropTypes } from 'react' |
| 2 | +import { HOC as hoc } from 'formsy-react' |
| 3 | +import cn from 'classnames' |
| 4 | + |
| 5 | +class CheckboxGroup extends Component { |
| 6 | + |
| 7 | + constructor(props) { |
| 8 | + super(props) |
| 9 | + this.changeValue = this.changeValue.bind(this) |
| 10 | + } |
| 11 | + |
| 12 | + changeValue() { |
| 13 | + const value = [] |
| 14 | + this.props.options.forEach((option, key) => { |
| 15 | + if (this['element-' + key].checked) { |
| 16 | + value.push(option.value) |
| 17 | + } |
| 18 | + }) |
| 19 | + this.props.setValue(value) |
| 20 | + this.props.onChange(this.props.name, value) |
| 21 | + } |
| 22 | + |
| 23 | + render() { |
| 24 | + const { label, name, options } = this.props |
| 25 | + const hasError = !this.props.isPristine() && !this.props.isValid() |
| 26 | + const disabled = this.props.isFormDisabled() || this.props.disabled |
| 27 | + const errorMessage = this.props.getErrorMessage() || this.props.validationError |
| 28 | + |
| 29 | + const renderOption = (cb, key) => { |
| 30 | + const curValue = this.props.getValue() || [] |
| 31 | + const checked = curValue.indexOf(cb.value) !== -1 |
| 32 | + const disabled = this.props.isFormDisabled() || cb.disabled || this.props.disabled |
| 33 | + const rClass = cn('checkbox-group-item', { disabled }) |
| 34 | + const id = name+'-opt-'+key |
| 35 | + const setRef = (c) => this['element-' + key] = c |
| 36 | + return ( |
| 37 | + <div className={rClass} key={key}> |
| 38 | + <div className="tc-checkbox"> |
| 39 | + <input |
| 40 | + id={id} |
| 41 | + ref={setRef} |
| 42 | + type="checkbox" |
| 43 | + name={name} |
| 44 | + checked={checked} |
| 45 | + disabled={disabled} |
| 46 | + onChange={this.changeValue} |
| 47 | + /> |
| 48 | + <label htmlFor={id}/> |
| 49 | + </div> |
| 50 | + <label className="tc-checkbox-label" htmlFor={id}>{cb.label}</label> |
| 51 | + </div> |
| 52 | + ) |
| 53 | + } |
| 54 | + |
| 55 | + return ( |
| 56 | + <div> |
| 57 | + <label className="checkbox-group-label">{label}</label> |
| 58 | + <div className="checkbox-group-options">{options.map(renderOption)}</div> |
| 59 | + { hasError ? (<p className="error-message">{errorMessage}</p>) : null} |
| 60 | + </div> |
| 61 | + ) |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +CheckboxGroup.PropTypes = { |
| 66 | + options: PropTypes.arrayOf(PropTypes.object).isRequired |
| 67 | +} |
| 68 | + |
| 69 | +CheckboxGroup.defaultProps = { |
| 70 | + onChange: () => {} |
| 71 | +} |
| 72 | + |
| 73 | +export default hoc(CheckboxGroup) |
0 commit comments