Skip to content

Commit

Permalink
refactor: improve type safety for Checkbox component
Browse files Browse the repository at this point in the history
- Ensure compatibility with Radix UI's CheckedState type
- Enhance type safety with exactOptionalPropertyTypes option
  • Loading branch information
jiji-hoon96 committed Jan 21, 2025
1 parent a6a2a04 commit 5fda386
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions packages/checkbox/src/Checkbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export interface CheckboxProps
extends Omit<ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>, 'asChild'> {
label?: string;
size?: CheckboxSize;
value?: string;
}

export interface CheckboxGroupProps {
Expand Down Expand Up @@ -98,8 +99,8 @@ Checkbox.displayName = 'Checkbox';

export const CheckboxGroup = forwardRef<HTMLDivElement, CheckboxGroupProps>(
({ children, name, onChange, value }, ref) => {
const handleCheckedChange = (checked: boolean, itemValue: string | undefined) => {
if (!onChange || !itemValue) return;
const handleCheckedChange = (checked: CheckboxPrimitive.CheckedState, itemValue: string | undefined) => {
if (!onChange || !itemValue || typeof checked !== 'boolean') return;

const newValues = checked
? [...(value || []), itemValue]
Expand All @@ -109,15 +110,18 @@ export const CheckboxGroup = forwardRef<HTMLDivElement, CheckboxGroupProps>(
};

const mappedChildren = Children.map(children, (child) => {
if (!isValidElement(child)) return child;
if (!isValidElement<CheckboxProps>(child)) return child;

const checked = value?.includes(child.props.value);
const checked = value?.includes(child.props.value || '') || false;

return cloneElement(child, {
checked,
name,
onCheckedChange: (checked: boolean) => handleCheckedChange(checked, child.props.value),
});
onCheckedChange: (state: CheckboxPrimitive.CheckedState) => {
handleCheckedChange(state, child.props.value);
child.props.onCheckedChange?.(state);
},
} as Partial<CheckboxProps>);
});

return (
Expand All @@ -128,4 +132,4 @@ export const CheckboxGroup = forwardRef<HTMLDivElement, CheckboxGroupProps>(
}
);

CheckboxGroup.displayName = 'CheckboxGroup';
CheckboxGroup.displayName = 'CheckboxGroup';

0 comments on commit 5fda386

Please sign in to comment.