CheckboxSelection.tsx 2.37 KB
Newer Older
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
import * as React from 'react';
import { translate } from 'react-i18next';

import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormLabel from '@material-ui/core/FormLabel';
import FormControl from '@material-ui/core/FormControl';
import RadioGroup from '@material-ui/core/RadioGroup';
import { withStyles } from '@material-ui/core/styles';
import Checkbox from '@material-ui/core/Checkbox';

/* tslint:disable */
const styles = (theme) =>({
  radioGroupMultiColumn: {
    flexDirection: 'row' as 'row',
    justifyContent: 'space-between' as 'space-between',
    '& > label': {
      flexBasis: '12%',
      [theme.breakpoints.down('lg')]: {
        flexBasis: '24%',
      },
      [theme.breakpoints.down('md')]: {
        flexBasis: '32%',
      },
      [theme.breakpoints.down('sm')]: {
        flexBasis: '45%',
      },
      [theme.breakpoints.down('xs')]: {
        flexBasis: '100%',
      },
    },
  },
});
/* tslint:enable */

const handleCheckboxChange = (fields, code)  => {
  const index = fields.getAll() ? fields.getAll().indexOf(code) : -1;

  if (index === -1) {
    fields.push(code);
  } else {
    fields.remove(index);
  }
};

const CheckboxSelection = ({formLabel, singleColumn = false, options, renderOptionLabel, valueField, fields, input, meta, classes, t, ...rest}) => (
  <FormControl required className={ classes.root } fullWidth>
    <FormLabel className={ classes.formLabel }>{ formLabel }</FormLabel>
    <RadioGroup
      { ...input }
      { ...rest }
      className={ singleColumn ? classes.radioGroupSingleColumn : classes.radioGroupMultiColumn }
    >
      { options && options.length > 0 &&
      options.map((option, i) => (
        <FormControlLabel
          key={ `radio_option_${i}` }
          value={ valueField ? option[valueField] : option }
          label={ renderOptionLabel ? renderOptionLabel(option) : valueField ? option[valueField] : option }
          control={
            <Checkbox
              checked={ fields.getAll() && fields.getAll().indexOf(valueField ? option[valueField] : option) !== -1 }
              onChange={ (event, value) => handleCheckboxChange(fields,valueField ? option[valueField] : option) } // tslint:disable-line
            />
          }
          className={ classes.label }
        />
      ))
      }
    </RadioGroup>
  </FormControl>
);

export default withStyles(styles)(translate()(CheckboxSelection));