| Total Complexity | 2 |
| Complexity/F | 0 |
| Lines of Code | 67 |
| Function Count | 0 |
| Duplicated Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
| 1 | import { Field, useField } from "formik"; |
||
| 2 | import React, { useEffect } from "react"; |
||
| 3 | import { FormattedMessage } from "react-intl"; |
||
| 4 | import { focusOnElement } from "../../helpers/forms"; |
||
| 5 | import { inputMessages } from "./Messages"; |
||
| 6 | |||
| 7 | interface CheckboxGroupFieldProps { |
||
| 8 | groupLabel: string; |
||
| 9 | name: string; |
||
| 10 | allBoxes: { |
||
| 11 | value: string | number; |
||
| 12 | label: string; |
||
| 13 | }[]; |
||
| 14 | /** data-clone grid sizing value to be applied to individual boxes; see https://designwithclone.ca/#flexbox-grid */ |
||
| 15 | grid?: string; |
||
| 16 | required?: boolean; |
||
| 17 | } |
||
| 18 | |||
| 19 | export const CheckboxGroupField: React.FC<CheckboxGroupFieldProps> = ({ |
||
| 20 | groupLabel, |
||
| 21 | grid, |
||
| 22 | name, |
||
| 23 | allBoxes, |
||
| 24 | required, |
||
| 25 | }) => { |
||
| 26 | const [field, meta] = useField(name); |
||
| 27 | const hasError = !!meta.error && meta.touched; |
||
| 28 | useEffect(() => { |
||
| 29 | if (hasError) { |
||
| 30 | focusOnElement(`${allBoxes[0].value}`); |
||
| 31 | } |
||
| 32 | }); |
||
| 33 | return ( |
||
| 34 | <fieldset |
||
| 35 | data-c-input="checkbox(group)" |
||
| 36 | className="clone-checkbox-group" |
||
| 37 | data-c-required={required || null} |
||
| 38 | data-c-invalid={meta.touched && meta.error ? true : null} |
||
| 39 | > |
||
| 40 | <legend>{groupLabel}</legend> |
||
| 41 | <span> |
||
| 42 | <FormattedMessage {...inputMessages.required} /> |
||
| 43 | </span> |
||
| 44 | <div data-c-grid> |
||
| 45 | {allBoxes.map((box) => { |
||
| 46 | return ( |
||
| 47 | <div key={box.value} data-c-grid-item={grid}> |
||
| 48 | <label> |
||
| 49 | <Field |
||
| 50 | id={box.value} |
||
| 51 | type="checkbox" |
||
| 52 | name={name} |
||
| 53 | value={box.value} |
||
| 54 | /> |
||
| 55 | <span>{box.label}</span> |
||
| 56 | </label> |
||
| 57 | </div> |
||
| 58 | ); |
||
| 59 | })} |
||
| 60 | </div> |
||
| 61 | <span>{meta.error}</span> |
||
| 62 | </fieldset> |
||
| 63 | ); |
||
| 64 | }; |
||
| 65 | |||
| 66 | export default CheckboxGroupField; |
||
| 67 |