{"size": 1447, "ext": "js", "max_stars_repo_path": "src/components/CheckBoxList.js", "max_stars_repo_name": "airbus-driver/take-home", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/components/CheckBoxList.js", "max_issues_repo_name": "airbus-driver/take-home", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/components/CheckBoxList.js", "max_forks_repo_name": "airbus-driver/take-home", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.3090909091, "max_line_length": 175, "alphanum_fraction": 0.6268140981}
import React, { useState } from 'react';
import styled from 'styled-components';

import Input from './Input';

const CheckBoxContainer = styled.ul`
  border: 1px solid ${({ theme }) => theme.colors.border};
  padding: 0;
  margin: 0;
  background-color: #fff;
  width: 100%;
  background: inherit;

  &:focus-within {
    outline: none;
    border: 1px solid ${({ theme }) => theme.colors.borderFocus};
  }
`;

const CheckBoxItem = styled.li`
  padding: 5px;
  display: flex;
  align-items: center;
`;

const CheckBoxList = ({ options, value, onFieldChange, ...props }) => {
  const { name, tabIndex } = props;
  const [selectedValues, setSelectedValues] = useState(value);

  const handleOnChange = (e) => {
    const val = e.target.value;
    let arr = [];
    if (selectedValues.includes(val)) {
      arr = selectedValues.filter(s => s !== val);
    } else {
      arr = [...selectedValues, val];
    }
    setSelectedValues(arr);
    onFieldChange(arr);
  };

  return (
    <CheckBoxContainer tabIndex={tabIndex}>
      {options.map((item, index) => (
        <CheckBoxItem key={`cbl-${item.value}-${index}`} value={item.value}>
          <Input name={`${name}.${item.value}`} type="checkbox" value={item.value} checked={selectedValues && selectedValues.includes(item.value)} onChange={handleOnChange} />
          <label>{item.label}</label>
        </CheckBoxItem>
      ))}
    </CheckBoxContainer>
  );
};

export default CheckBoxList;
