diff --git a/.changeset/eleven-monkeys-teach.md b/.changeset/eleven-monkeys-teach.md new file mode 100644 index 0000000000..d92a49b72b --- /dev/null +++ b/.changeset/eleven-monkeys-teach.md @@ -0,0 +1,5 @@ +--- +'@leafygreen-ui/checkbox': minor +--- + +Allow defaultChecked to be used in Checkbox diff --git a/packages/checkbox/src/Checkbox/Checkbox.spec.tsx b/packages/checkbox/src/Checkbox/Checkbox.spec.tsx index c5b191367e..e9c9f15d4d 100644 --- a/packages/checkbox/src/Checkbox/Checkbox.spec.tsx +++ b/packages/checkbox/src/Checkbox/Checkbox.spec.tsx @@ -52,6 +52,14 @@ describe('packages/checkbox', () => { expect(checkbox.getAttribute('aria-checked')).toBe('false'); }); + test('renders as checked when defaultChecked prop is set', () => { + const { checkbox, getInputValue } = renderCheckbox({ + defaultChecked: true, + }); + expect(getInputValue()).toBe(true); + expect(checkbox.getAttribute('aria-checked')).toBe('true'); + }); + test('renders as checked when the prop is set', () => { const { checkbox, getInputValue } = renderCheckbox({ checked: true }); expect(getInputValue()).toBe(true); @@ -144,5 +152,13 @@ describe('packages/checkbox', () => { fireEvent.click(checkbox); expect(getInputValue()).toBe(true); }); + + test('checkbox becomes unchecked when clicked if defaultChecked is set', () => { + const { checkbox, getInputValue } = renderCheckbox({ + defaultChecked: true, + }); + fireEvent.click(checkbox); + expect(getInputValue()).toBe(false); + }); }); }); diff --git a/packages/checkbox/src/Checkbox/Checkbox.tsx b/packages/checkbox/src/Checkbox/Checkbox.tsx index b2bb11071c..e45ae2d519 100644 --- a/packages/checkbox/src/Checkbox/Checkbox.tsx +++ b/packages/checkbox/src/Checkbox/Checkbox.tsx @@ -49,6 +49,7 @@ function Checkbox({ id: idProp, indeterminate: indeterminateProp, label = '', + defaultChecked = false, onClick: onClickProp, onChange: onChangeProp, name, @@ -58,7 +59,7 @@ function Checkbox({ const { darkMode, theme } = useDarkMode(darkModeProp); const baseFontSize = useUpdatedBaseFontSize(baseFontSizeProp); - const [checked, setChecked] = React.useState(false); + const [checked, setChecked] = React.useState(defaultChecked); const isChecked = React.useMemo( () => (checkedProp != null ? checkedProp : checked), [checkedProp, checked],