A toggle that allows users to choose between checked and unchecked states.
import { Checkbox } from "#/ui/components/Checkbox"
<Checkbox />
You can pass a label to your checkbox to automatically associate it with the checkbox.
<Checkbox label="Accept terms and conditions" defaultChecked />
If you need a checkbox with accessible text that isn’t visible, you can hide the label
<Checkbox label="Accept terms and conditions" hideLabel defaultChecked />
Optionally, if you need your label separated from your checkbox, you can associate them by using the id
and htmlFor
props.
You can change the size of your checkbox by passing the size
prop.
<Checkbox
size="sm" // sm, md, lg
label="size sm"
hideLabel
defaultChecked
/>
You can pass a custom icon if you want to change the default check
<Checkbox label="custom icon example" hideLabel defaultChecked>
<FaceHappyIcon slot="icon" />
</Checkbox>
You may need to adjust the size of your icon to fit the checkbox (this isn’t done for you for custom icons)
You can control the state of the checkbox from outside of the component by passing the checked
and onChange
props.
export const Controlled = () => {
const [checked, setChecked] = useState(false)
return (
<Checkbox
label="controlled example"
checked={checked}
onChange={() => setChecked(!checked)}
/>
)
}
While a checkbox can only accept 2 states in a form, checked or unchecked, there may be other situations where showing an indeterminate (or partially selected) state might make sense.
export const Indeterminate = () => {
const [checked, setChecked] = useState("indeterminate")
return (
<Checkbox
id="email"
label="Accept terms and conditions"
checked={checked}
icon={
checked === "indeterminate" ? (
<MinusIcon />
) : checked ? (
<CheckIcon />
) : undefined
}
onChange={() =>
checked === "indeterminate"
? setChecked(true)
: checked
? setChecked(false)
: setChecked("indeterminate")
}
/>
)
}
If you’d like to extend the checkbox to make a larger clickable area, you can use the CheckboxCard
component.
<CheckboxCard client:load defaultChecked showCheckbox className="max-w-md flex items-start">
<div className="text-left">
<label htmlFor="custom-checkbox" className="font-bold">
Checkbox Card
</label>
<p className="text-sm text-gray-500">Try clicking this to see the checkbox in action</p>
</div>
</CheckboxCard>
See more at CheckboxCard