All files / lib/CheckboxGroup index.js

82.61% Statements 19/23
50% Branches 2/4
77.78% Functions 7/9
90.48% Lines 19/21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83                                  4x 4x           1x 1x 1x   1x       1x 1x     1x           5x 5x   5x 5x 9x 9x       1x         5x       89x                             89x            
import React from 'react';
import PropTypes from 'prop-types';
 
/**
 * @category controls
 * @component checkbox
 * @variations collab-ui-react
 */
 
class CheckboxGroup extends React.Component {
  static displayName = 'CheckboxGroup';
 
  state = {
    values: []
  }
 
  componentWillMount() {
    Eif (this.props.values) {
      this.setState({ values: this.props.values });
    }
  }
 
  handleToggle = value => {
    let newValues;
    const { onChange } = this.props;
    const { values } = this.state;
    const isActive = values.includes(value);
 
    Iif (isActive) {
      newValues = values.filter(v => v !== value);
      onChange(this.props.values.filter(n => n !== value));
    } else {
      newValues = values.concat(value);
      onChange([...this.props.values, value]);
    }
 
    this.setState({
      values: newValues,
    });
  }
 
  render() {
    const { children, name } = this.props;
    const { values } = this.state;
 
    const addHandlersToChildren = () => {
      return React.Children.map(children, child => {
        const { value } = child.props;
        return React.cloneElement(child, {
          name: name,
          checked: values.includes(value),
          'aria-checked': values.includes(value),
          onChange: () => this.handleToggle(value),
        });
      });
    };
 
    return <div className={`cui-checkbox-group`}>{addHandlersToChildren()}</div>;
  }
}
 
CheckboxGroup.propTypes = {
  /** @prop Children nodes to render inside Accordion | null */
  children: PropTypes.node,
  /** @prop Callback fired with the value or array of active values when the user presses a button | null
   * @controllable values
  */
  onChange: PropTypes.func,
  /** @prop An array of values, of the active (pressed) buttons | () => {}
   * @controllable onChange
   */
  values: PropTypes.array,
  /** @prop An HTML `<input>` name for each child button | '' */
  name: PropTypes.string,
};
 
CheckboxGroup.defaultProps = {
  values: [],
  onChange: () => {},
  name: '',
};
 
export default CheckboxGroup;