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