Skip to content

Commit

Permalink
Allow defaultChecked to be used in Checkbox (#2600)
Browse files Browse the repository at this point in the history
* Allow defaultChecked to be used in Checkbox

* Update eleven-monkeys-teach.md

---------

Co-authored-by: Brooke Scarlett Yalof <[email protected]>
Co-authored-by: Adam Thompson <[email protected]>
  • Loading branch information
3 people authored Feb 4, 2025
1 parent 674d068 commit 50ea705
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/eleven-monkeys-teach.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@leafygreen-ui/checkbox': minor
---

Allow defaultChecked to be used in Checkbox
16 changes: 16 additions & 0 deletions packages/checkbox/src/Checkbox/Checkbox.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
});
});
});
3 changes: 2 additions & 1 deletion packages/checkbox/src/Checkbox/Checkbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ function Checkbox({
id: idProp,
indeterminate: indeterminateProp,
label = '',
defaultChecked = false,
onClick: onClickProp,
onChange: onChangeProp,
name,
Expand All @@ -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],
Expand Down

0 comments on commit 50ea705

Please sign in to comment.