Checkbox
A box someone can tick to turn a single option on or off, supporting help text, an indeterminate mixed state, errors and a disabled state.
Preview
Code
Example.jsx
import { useState, useCallback } from 'react';
import { Card, Box, BlockStack, Checkbox, Text, Divider } from '@shopify/polaris';
const SALES_CHANNELS = [
{ id: 'online-store', label: 'Online Store', helpText: 'Your themed storefront at example.myshopify.com.' },
{ id: 'pos', label: 'Point of Sale', helpText: 'Sell this product in your retail locations.' },
{ id: 'shop', label: 'Shop app', helpText: null },
];
export const Example = () => {
const [channels, setChannels] = useState({ 'online-store': true, pos: false, shop: true });
const [terms, setTerms] = useState(false);
const [submitted, setSubmitted] = useState(true);
const selectedCount = Object.values(channels).filter(Boolean).length;
const allSelected = selectedCount === SALES_CHANNELS.length;
const parentChecked = allSelected ? true : selectedCount > 0 ? 'indeterminate' : false;
const toggleAll = useCallback(() => {
setChannels((prev) => {
const next = Object.values(prev).every(Boolean) ? false : true;
return SALES_CHANNELS.reduce((acc, channel) => ({ ...acc, [channel.id]: next }), {});
});
}, []);
const toggleChannel = useCallback((id) => {
setChannels((prev) => ({ ...prev, [id]: !prev[id] }));
}, []);
return (
<Card>
<BlockStack gap="400">
<Text as="h2" variant="headingMd">
Sales channels
</Text>
<BlockStack gap="200">
<Checkbox
label="All sales channels"
checked={parentChecked}
onChange={toggleAll}
helpText={`${selectedCount} of ${SALES_CHANNELS.length} selected`}
/>
<Box paddingInlineStart="600">
<BlockStack gap="200">
{SALES_CHANNELS.map((channel) => (
<Checkbox
key={channel.id}
label={channel.label}
helpText={channel.helpText}
checked={channels[channel.id]}
onChange={() => toggleChannel(channel.id)}
/>
))}
</BlockStack>
</Box>
</BlockStack>
<Divider />
<BlockStack gap="200">
<Checkbox
label="I agree to the merchant terms of service"
checked={terms}
onChange={(value) => {
setTerms(value);
setSubmitted(true);
}}
error={submitted && !terms ? 'You must accept the terms before publishing.' : undefined}
/>
<Checkbox
label="Charge tax on this product"
checked
disabled
helpText="Managed by your store tax settings."
onChange={() => {}}
/>
</BlockStack>
</BlockStack>
</Card>
);
};