All files / src/components/Form/CheckboxList index.jsx

5.56% Statements 1/18
0% Branches 0/4
0% Functions 0/10
5.88% Lines 1/17
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                                                                                                          3x                            
import 'react-select/dist/react-select.css';
 
import React, { PureComponent } from 'react';
import { HOC as formsyDecorator } from 'formsy-react';
import Field from '../Field';
import Checkbox from './Checkbox';
import PropTypes from 'prop-types';
 
class CheckboxList extends PureComponent {
  static cmp(a, b) {
    return a === b;
  }
 
  componentDidMount() {
    this.props.setValue([]);
  }
 
  handleChange(e, option) {
    const checked = e.currentTarget.checked;
 
    let newValue = [];
    if (checked) {
      newValue = this.props.getValue().concat(option);
    } else {
      newValue = this.props.getValue().filter((it) => ! CheckboxList.cmp(it, option));
    }
 
    this.props.setValue(newValue);
  }
 
  render() {
    const { name, label, items, validations, validationError } = this.props;
    const checked = this.props.getValue() || [];
 
    return <Field label={label}
        getErrorMessage={() => this.props.getErrorMessage()}
        showError={() => this.props.showError()}
        validations={validations}
        validationError={validationError}
        showRequired={() => this.props.showRequired()}>
      {
        items.map((item) =>
          <Checkbox key={name}
              name={name}
              item={item}
              onChecked={(e) => this.handleChange(e, item)}
              checked={checked.indexOf(item) >= 0} />)
      }
    </Field>;
  }
 
}
 
CheckboxList.propTypes = {
  setValue: PropTypes.func.isRequired,
  getValue: PropTypes.func.isRequired,
  name: PropTypes.string,
  label: PropTypes.string,
  items: PropTypes.array,
  getErrorMessage: PropTypes.func.isRequired,
  showRequired: PropTypes.func.isRequired,
  showError: PropTypes.func.isRequired,
  validations: PropTypes.string,
  validationError: PropTypes.string,
};
 
export default formsyDecorator(CheckboxList);