Skip to content

Commit

Permalink
[@mantine/core] Checkbox: Fix Checkbox.Card component not working wit…
Browse files Browse the repository at this point in the history
…h `form.getInputProps`
  • Loading branch information
rtivital committed Nov 28, 2024
1 parent 99f531e commit 9c622e4
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useState } from 'react';
import { useForm } from '@mantine/form';
import { CheckboxGroup } from '../CheckboxGroup/CheckboxGroup';
import { CheckboxIndicator } from '../CheckboxIndicator/CheckboxIndicator';
import { CheckboxCard } from './CheckboxCard';
Expand Down Expand Up @@ -46,3 +47,22 @@ export function WithinGroup() {
</div>
);
}

export function WithUseForm() {
const form = useForm({ mode: 'uncontrolled', initialValues: { checkbox: true } });

return (
<div style={{ padding: 40 }}>
<CheckboxCard
p="md"
{...form.getInputProps('checkbox', { type: 'checkbox' })}
key={form.key('checkbox')}
>
<CheckboxIndicator />
Some label
</CheckboxCard>

{JSON.stringify(form.values)}
</div>
);
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useUncontrolled } from '@mantine/hooks';
import {
BoxProps,
createVarsResolver,
Expand All @@ -24,9 +25,15 @@ export interface CheckboxCardProps
extends BoxProps,
StylesApiProps<CheckboxCardFactory>,
ElementProps<'button', 'onChange'> {
/** Checked state */
/** Controlled component value */
checked?: boolean;

/** Uncontrolled component default value */
defaultChecked?: boolean;

/** Called when value changes */
onChange?: (checked: boolean) => void;

/** Determines whether the card should have border, `true` by default */
withBorder?: boolean;

Expand Down Expand Up @@ -68,6 +75,8 @@ export const CheckboxCard = factory<CheckboxCardFactory>((_props, ref) => {
withBorder,
value,
onClick,
defaultChecked,
onChange,
...others
} = props;

Expand All @@ -87,20 +96,28 @@ export const CheckboxCard = factory<CheckboxCardFactory>((_props, ref) => {

const ctx = useCheckboxGroupContext();
const _checked =
typeof checked === 'boolean' ? checked : ctx?.value.includes(value || '') || false;
typeof checked === 'boolean' ? checked : ctx?.value.includes(value || '') || undefined;

const [_value, setValue] = useUncontrolled({
value: _checked,
defaultValue: defaultChecked,
finalValue: false,
onChange,
});

return (
<CheckboxCardProvider value={{ checked: _checked }}>
<CheckboxCardProvider value={{ checked: _value }}>
<UnstyledButton
ref={ref}
mod={[{ 'with-border': withBorder, checked: _checked }, mod]}
mod={[{ 'with-border': withBorder, checked: _value }, mod]}
{...getStyles('card')}
{...others}
role="checkbox"
aria-checked={_checked}
aria-checked={_value}
onClick={(event) => {
onClick?.(event);
ctx?.onChange(value || '');
setValue(!_value);
}}
/>
</CheckboxCardProvider>
Expand Down

0 comments on commit 9c622e4

Please sign in to comment.