Saltar al contenido principal

Resumen

Use Checkbox cuando cada opción pueda seleccionarse de forma independiente. Para una elección mutuamente excluyente, use RadioGroup.

”Uso”

Estado no controlado

Usa defaultChecked para establecer el estado inicial de selección. La casilla de verificación controla los cambios posteriores.
Una casilla de verificación marcada y con nombre aporta su valor a un formulario. Establezca uncheckedValue si el formulario también debe enviar un valor cuando esté desmarcada.

Apariencia e interacción

Compare los estados seleccionado, indeterminado y deshabilitado y, a continuación, elija el color, el tamaño, la forma y la variante de forma independiente. Los ejemplos habilitados se pueden alternar. Tab enfoca la casilla de verificación y Espacio cambia su estado. Al hacer clic en su etiqueta también cambia su estado. Use disabled para impedir la interacción, o readOnly cuando el valor deba permanecer sin cambios mientras el control siga pudiendo enfocarse. Mantenga el significado en la etiqueta en lugar de comunicarlo solo mediante el color.

Estado controlado

Pasa checked y actualízalo con onCheckedChange para controlar la misma preferencia en el estado de React. La devolución de llamada recibe el siguiente valor booleano y los detalles del evento.

Estado indeterminado

Una casilla de verificación indeterminada representa una selección parcial. Derívalo de las opciones secundarias independientemente del estado de selección de la casilla de verificación.

Partes y contenido personalizado

Checkbox ensambla la raíz con estilo y sus iconos predeterminados de marcado e indeterminado. Usa Checkbox.Root con Checkbox.Indicator para controlar el contenido del indicador. Root controla el estado y la apariencia de la caja; Indicator renderiza el contenido que proporcionas.
CheckboxRootProps y CheckboxIndicatorProps son tipos públicos exportados desde twenty-ui/primitives/input. Ambas partes aceptan atributos nativos, controladores, refs, render y callbacks de className y style basadas en el estado. La ref de Root apunta al control visible; inputRef apunta al input nativo. La ref de la parte apunta a su elemento renderizado. Pasa nativeButton con render={<button />} al reemplazar Root por un botón. Las props de apariencia pertenecen a Root; las clases y estilos explícitos se combinan con los predeterminados. Indicator recibe el estado marcado e indeterminado, incluido el estado de transición. Establece keepMounted para conservar un indicador no marcado en el DOM; el estilo predeterminado lo oculta con opacidad. Anula su style o className para transiciones personalizadas. El ensamblaje invocable y su tipo CheckboxProps siguen siendo compatibles. Reemplaza el ensamblaje por Root y su parte al proporcionar iconos personalizados, en lugar de añadir otra parte a los elementos hijos del ensamblaje. Para el restablecimiento controlado de formularios, controla el onReset del formulario y restaura checked a tu valor inicial. Base UI 1.8 no restaura el estado de componentes no controlados al restablecer formularios de forma nativa. required, form, value y uncheckedValue mantienen el comportamiento del input nativo subyacente.

”Props”

La referencia se genera a partir de los tipos de componentes públicos. Los atributos nativos, incluidos los nombres accesibles y los manejadores de eventos, también se aceptan en las partes que representan elementos.
boolean
Whether the checkbox is currently ticked.To render an uncontrolled checkbox, use the defaultChecked prop instead.
string | ((state: CheckboxRootState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
"accent" | "success" | "warning"
predeterminado:"accent"
Color used while the checkbox is checked or indeterminate.
boolean
predeterminado:"false"
Whether the checkbox is initially ticked.To render a controlled checkbox, use the checked prop instead.
boolean
predeterminado:"false"
Whether the component should ignore user interaction.
string
Identifies the form that owns the hidden input. Useful when the checkbox is rendered outside the form.
boolean
predeterminado:"true"
Adds padding and a hover background around the box.
string
The id of the input element.
boolean
predeterminado:"false"
Whether the checkbox is in a mixed state: neither ticked, nor unticked.
Ref<HTMLInputElement>
A ref to access the hidden <input> element.
string
Identifies the field when a form is submitted.
boolean
predeterminado:"false"
Whether the component renders a native <button> element when replacing it via the render prop. Set to true if the rendered element is a native button.
((checked: boolean, eventDetails: { reason: "none"; event: Event; cancel: () => void; allowPropagation: () => void; isCanceled: boolean; isPropagationAllowed: boolean; trigger: Element | undefined; }) => void)
Event handler called when the checkbox is ticked or unticked.
boolean
predeterminado:"false"
Whether the checkbox controls a group of child checkboxes.Must be used in a Checkbox Group.
boolean
predeterminado:"false"
Whether the user should be unable to tick or untick the checkbox.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, CheckboxRootState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
boolean
predeterminado:"false"
Whether the user must tick the checkbox before submitting a form.
"round" | "square"
predeterminado:"square"
Corner shape of the box.
"md" | "sm"
predeterminado:"sm"
Visual size of the checkbox.
CSSProperties | ((state: CheckboxRootState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.
string
The value submitted with the form when the checkbox is unchecked. By default, unchecked checkboxes do not submit any value, matching native checkbox behavior.
string
The checkbox’s value. Identifies it within a Checkbox Group, falling back to name when omitted. When submitting a form, a checked box submits value; with no value, it submits the native “on”.
"outline" | "soft" | "solid"
predeterminado:"solid"
Visual style of the box: filled, outlined, or tinted.

Checkbox.Root

boolean
Whether the checkbox is currently ticked.To render an uncontrolled checkbox, use the defaultChecked prop instead.
string | ((state: CheckboxRootState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
"accent" | "success" | "warning"
predeterminado:"accent"
Color used while the checkbox is checked or indeterminate.
boolean
predeterminado:"false"
Whether the checkbox is initially ticked.To render a controlled checkbox, use the checked prop instead.
boolean
predeterminado:"false"
Whether the component should ignore user interaction.
string
Identifies the form that owns the hidden input. Useful when the checkbox is rendered outside the form.
boolean
predeterminado:"true"
Adds padding and a hover background around the box.
string
The id of the input element.
boolean
predeterminado:"false"
Whether the checkbox is in a mixed state: neither ticked, nor unticked.
Ref<HTMLInputElement>
A ref to access the hidden <input> element.
string
Identifies the field when a form is submitted.
boolean
predeterminado:"false"
Whether the component renders a native <button> element when replacing it via the render prop. Set to true if the rendered element is a native button.
((checked: boolean, eventDetails: { reason: "none"; event: Event; cancel: () => void; allowPropagation: () => void; isCanceled: boolean; isPropagationAllowed: boolean; trigger: Element | undefined; }) => void)
Event handler called when the checkbox is ticked or unticked.
boolean
predeterminado:"false"
Whether the checkbox controls a group of child checkboxes.Must be used in a Checkbox Group.
boolean
predeterminado:"false"
Whether the user should be unable to tick or untick the checkbox.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, CheckboxRootState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
boolean
predeterminado:"false"
Whether the user must tick the checkbox before submitting a form.
"round" | "square"
predeterminado:"square"
Corner shape of the box.
"md" | "sm"
predeterminado:"sm"
Visual size of the checkbox.
CSSProperties | ((state: CheckboxRootState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.
string
The value submitted with the form when the checkbox is unchecked. By default, unchecked checkboxes do not submit any value, matching native checkbox behavior.
string
The checkbox’s value. Identifies it within a Checkbox Group, falling back to name when omitted. When submitting a form, a checked box submits value; with no value, it submits the native “on”.
"outline" | "soft" | "solid"
predeterminado:"solid"
Visual style of the box: filled, outlined, or tinted.

Checkbox.Indicator

string | ((state: CheckboxIndicatorState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean
predeterminado:"false"
Whether to keep the element in the DOM when the checkbox is not checked.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, CheckboxIndicatorState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: CheckboxIndicatorState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.