forked from primer/react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CheckboxGroup.tsx
76 lines (67 loc) · 2.69 KB
/
CheckboxGroup.tsx
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
74
75
76
import React, {ChangeEvent, ChangeEventHandler, createContext, FC} from 'react'
import CheckboxOrRadioGroup, {CheckboxOrRadioGroupProps} from './_CheckboxOrRadioGroup'
import CheckboxOrRadioGroupCaption from './_CheckboxOrRadioGroup/_CheckboxOrRadioGroupCaption'
import CheckboxOrRadioGroupLabel from './_CheckboxOrRadioGroup/_CheckboxOrRadioGroupLabel'
import CheckboxOrRadioGroupValidation from './_CheckboxOrRadioGroup/_CheckboxOrRadioGroupValidation'
import {useRenderForcingRef} from './hooks'
import {SxProp} from './sx'
import {Checkbox, FormControl} from '.'
type CheckboxGroupProps = {
/**
* An onChange handler that gets called when any of the checkboxes change
*/
onChange?: (selected: string[], e?: ChangeEvent<HTMLInputElement>) => void
} & CheckboxOrRadioGroupProps &
SxProp
export const CheckboxGroupContext = createContext<{
disabled?: boolean
onChange?: ChangeEventHandler<HTMLInputElement>
}>({})
const CheckboxGroup: FC<CheckboxGroupProps> = ({children, disabled, onChange, ...rest}) => {
const formControlComponentChildren = React.Children.toArray(children)
.filter(child => React.isValidElement(child) && child.type === FormControl)
.map(formControlComponent =>
React.isValidElement(formControlComponent) ? formControlComponent.props.children : []
)
.flat()
const checkedCheckboxes = React.Children.toArray(formControlComponentChildren)
.filter(child => React.isValidElement(child) && child.type === Checkbox)
.map(
checkbox =>
React.isValidElement(checkbox) &&
(checkbox.props.checked || checkbox.props.defaultChecked) &&
checkbox.props.value
)
.filter(Boolean)
const [selectedCheckboxValues, setSelectedCheckboxValues] = useRenderForcingRef<string[]>(checkedCheckboxes)
const updateSelectedCheckboxes: ChangeEventHandler<HTMLInputElement> = e => {
const {value, checked} = e.currentTarget
if (checked) {
setSelectedCheckboxValues([...(selectedCheckboxValues.current || []), value])
return
}
setSelectedCheckboxValues((selectedCheckboxValues.current || []).filter(selectedValue => selectedValue !== value))
}
return (
<CheckboxGroupContext.Provider
value={{
disabled,
onChange: e => {
if (onChange) {
updateSelectedCheckboxes(e)
onChange(selectedCheckboxValues.current || [], e)
}
}
}}
>
<CheckboxOrRadioGroup disabled={disabled} {...rest}>
{children}
</CheckboxOrRadioGroup>
</CheckboxGroupContext.Provider>
)
}
export default Object.assign(CheckboxGroup, {
Caption: CheckboxOrRadioGroupCaption,
Label: CheckboxOrRadioGroupLabel,
Validation: CheckboxOrRadioGroupValidation
})