All files / lib/RadioGroup index.js

95.24% Statements 20/21
50% Branches 2/4
100% Functions 7/7
95.24% Lines 20/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 84 85 86                                4x 4x           1x 1x 1x   1x 1x 1x         1x           5x 5x   5x 5x 9x 9x     1x         5x       89x                                 89x             89x      
import React from 'react';
import PropTypes from 'prop-types';
 
/**
 * @category controls
 * @component radio
 * @variations collab-ui-react
 */
 
class RadioGroup extends React.Component {
 
  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);
 
    Eif (!isActive) {
      newValues = [value];
      onChange(value);
    } else {
      return;
    }
 
    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),
          onChange: () => this.handleToggle(value),
        });
      });
    };
 
    return <div className={`cui-radio-group`}>{addHandlersToChildren()}</div>;
  }
}
 
RadioGroup.propTypes = {
  /** @prop Children nodes to render inside RadioGroup | null */
  children: PropTypes.node,
  /** @prop An HTML `<input>` name for each child button | '' */
  name: PropTypes.string,
  /** 
   * @prop Callback function called with value or array of values when invoked by user making a change with the RadioGroup | () => {}
   * @controllable values
  */
  onChange: PropTypes.func,
  /**
   * @prop Array of values, of the active (pressed) buttons | []
   * @controllable onChange
  */
  values: PropTypes.array,
};
 
RadioGroup.defaultProps = {
  children: null,
  name: '',
  onChange: () => {},
  values: [],
};
 
RadioGroup.displayName = 'RadioGroup';
 
export default RadioGroup;