import Layout from '../../components/Layout' import { ComponentsSidebar } from '../../sidebars' import { Playground } from '../../components/Playground'; import { Code, Heading, Paragraph } from '@knkui/typography'; export default function Checkbox() { return ( If you have multiple options appearing in a list, you can preserve space by using checkboxes instead of on/off switches. If you have a single option, avoid using a checkbox and use an on/off switch instead. Basic checkboxes ` } /> Indeterminate Set indeterminate to show partially checked states. The parent checkbox will be indeterminate until all its child sub-options are checked. { const childItems = Object.keys(checkedItems).filter(i => i !== PARENT_ID); return childItems.reduce( (count, i) => (checkedItems[i] ? count + 1 : count), 0, ); }; const getIsParentIndeterminate = (checkedItems) => { const checkedChildrenCount = getCheckedChildrenCount(checkedItems); return checkedChildrenCount > 0 && checkedChildrenCount < 2; }; const initialCheckedItems = { [PARENT_ID]: false, [CHILD_1_ID]: false, [CHILD_2_ID]: false, }; const [checkedItems, setCheckedItems] = React.useState(initialCheckedItems); const onChange = (event) => { const itemValue = event.target.value; if (itemValue === PARENT_ID) { const newCheckedState = !checkedItems[PARENT_ID]; // Set all items to the checked state of the parent setCheckedItems( Object.keys(checkedItems).reduce( (items, i) => ({ ...items, [i]: newCheckedState }), {}, ), ); } else { const newCheckedItems = { ...checkedItems, [itemValue]: !checkedItems[itemValue], }; setCheckedItems({ // If all children would be unchecked, also uncheck the parent ...newCheckedItems, [PARENT_ID]: getCheckedChildrenCount(newCheckedItems) > 0, }); } }; return (
) } ` } /> Uncontrolled In an uncontrolled checkbox, the checked state is managed by the DOM. Use defaultChecked to set the initial selected state. ` } /> Size Set size to change the size of the checkbox. ` } />
) }