diff --git a/src/design-system/components/checkbox/CheckBox.tsx b/src/design-system/components/checkbox/CheckBox.tsx index 6008ae00b..b5b835d17 100644 --- a/src/design-system/components/checkbox/CheckBox.tsx +++ b/src/design-system/components/checkbox/CheckBox.tsx @@ -1,20 +1,26 @@ import Checkbox, { CheckboxProps } from '@mui/material/Checkbox' -import { FC, ReactNode, useState } from 'react' +import { type ChangeEvent, type ReactNode, useCallback, useState } from 'react' import Loader from '~/components/loader/Loader' import { cn } from '~/utils/cn' import './CheckBox.scss' -interface CheckBoxProps extends Omit { +interface CheckBoxProps extends Omit { variant: 'check' | 'middle' label: ReactNode labelPosition?: 'top' | 'bottom' | 'end' color?: 'primary' | 'secondary' | 'error' | 'success' size?: 'sm' | 'md' | 'lg' loading?: boolean + checked?: boolean + defaultChecked?: boolean + onChange?: (checked: boolean) => void } -const CheckBox: FC = ({ +const CheckBox: React.FC = ({ + checked: externalIsChecked, + defaultChecked = false, + onChange, color = 'primary', disabled = false, label, @@ -24,11 +30,21 @@ const CheckBox: FC = ({ size = 'md', ...props }) => { - const [checked, setChecked] = useState(false) + const [internalIsChecked, setInternalIsChecked] = + useState(defaultChecked) - const handleChange = (event: React.ChangeEvent) => { - setChecked(event.target.checked) - } + const isCheckboxControlled = externalIsChecked !== undefined + + const handleChange = useCallback( + ({ target: { checked } }: ChangeEvent) => { + if (!isCheckboxControlled) { + setInternalIsChecked(checked) + } + + onChange?.(checked) + }, + [onChange, isCheckboxControlled] + ) const loaderSizeMapping: Record = { sm: 14, @@ -37,6 +53,9 @@ const CheckBox: FC = ({ } const loader = + const resolvedIsCheck = isCheckboxControlled + ? externalIsChecked + : internalIsChecked return (