import React, { useState } from 'react'; import styled from 'styled-components'; import FlexRow, { FlexRowProps } from '../../layout/FlexRow/FlexRow'; import FlexCol, { FlexColProps } from '../../layout/FlexCol/FlexCol'; import CheckboxField from '../CheckboxField/CheckboxField'; import ErrorMessage from '../../atoms/ErrorMessage/ErrorMessage'; import Fieldset from '../../atoms/Fieldset/Fieldset'; import Legend from '../../atoms/Legend/Legend'; const CheckboxWrapper = styled.div` padding: 4px 0; `; interface CheckboxGroupFieldItem> { label: string; name: keyof Val; defaultChecked?: boolean; disabled?: boolean; } export interface CheckboxGroupFieldProps> { label: string; items: CheckboxGroupFieldItem[]; onChange?: (value: Val) => void; onBlur?: () => void; disabled?: boolean; isValid?: boolean; value?: Val; errorMessage?: string; className?: string; flexColProps?: FlexColProps; flexRowProps?: FlexRowProps; hideControl?: boolean; 'data-automation'?: string; } const CheckboxGroupField = >({ items, label, onChange, onBlur, value, disabled, isValid = false, errorMessage, className, flexRowProps = {}, flexColProps = {}, hideControl, 'data-automation': dataAutomation, }: CheckboxGroupFieldProps) => { const [innerValue, setInnerValue] = useState( items.reduce( (acc, { name, defaultChecked }) => ({ ...acc, [name]: defaultChecked || false, }), {} as Val, ), ); const handleChange = (name: keyof Val) => () => { if (disabled) { return; } if (!value) { const newValue = { ...innerValue, [name]: !innerValue[name], }; setInnerValue(newValue); onChange && onChange(newValue); } else { onChange && onChange({ ...value, [name]: !value[name], }); } }; return (
{label} {items.map((item, index) => { const checked = value ? !!value[item.name] : !!innerValue[item.name]; return ( ); })} {errorMessage && ( {errorMessage} )}
); }; export default CheckboxGroupField;