const WithOnChangeHandlers = () => {
const [selectedCheckboxValues, setSelectedCheckboxValues] = React.useState(['one', 'two'])
const [lastSelectedCheckboxValue, setLastSelectedCheckboxValue] = React.useState()
const handleCheckboxGroupChange = (selectedValues, e) => {
setSelectedCheckboxValues(selectedValues)
setLastSelectedCheckboxValue(e.currentTarget.value)
}
const handleChoiceOneChange = e => {
alert('Choice one has its own handler')
}
return (
<Box display="grid" sx={{gap: 1}}>
<CheckboxGroup onChange={handleCheckboxGroupChange}>
<CheckboxGroup.Label>Choices</CheckboxGroup.Label>
<FormControl>
<Checkbox value="one" defaultChecked onChange={handleChoiceOneChange} />
<FormControl.Label>Choice one</FormControl.Label>
</FormControl>
<FormControl>
<Checkbox value="two" defaultChecked />
<FormControl.Label>Choice two</FormControl.Label>
</FormControl>
<FormControl>
<Checkbox value="three" />
<FormControl.Label>Choice three</FormControl.Label>
</FormControl>
</CheckboxGroup>
{Boolean(selectedCheckboxValues.length) && (
<div>The selected checkbox values are {selectedCheckboxValues.join(', ')}</div>
)}
{Boolean(lastSelectedCheckboxValue) && <div>The last affected checkbox value is {lastSelectedCheckboxValue}</div>}
</Box>
)
}
render(<WithOnChangeHandlers />)