Saltar al contenido principal

Resumen

Use Switch para una preferencia de encendido o apagado. Proporcione al control una etiqueta visible o un nombre accesible.

Uso

Estado no controlado

Usa defaultChecked para establecer el estado inicial de selección. El interruptor controla los cambios posteriores.

Opciones visuales

Compare los dos tamaños en los estados activado, desactivado, deshabilitado, de solo lectura y de foco. Use los ejemplos habilitados para probar la activación y desactivación.

Estado controlado

Pasa checked y actualízalo con onCheckedChange para controlar la misma preferencia en el estado de React.
onCheckedChange recibe el siguiente valor booleano y los detalles del evento. La prop size acepta sm o md y el valor predeterminado es md. Para una fila de ancho completo uniforme con un icono, una descripción y un interruptor, usa SettingsRow.

Teclado y formularios

Tab mueve el foco al interruptor; la barra espaciadora lo alterna. Al hacer clic en su etiqueta asociada también se alterna. Use disabled para impedir la interacción o readOnly para conservar un control que puede recibir el foco y cuyo valor no se puede cambiar. Un interruptor con nombre envía su valor cuando está activado. Use value para personalizar ese valor y uncheckedValue si el formulario también debe enviar un valor cuando está apagado.

Partes y contenido personalizado

Switch ensambla la raíz con estilo y su control deslizante predeterminado. Usa Switch.Root con Switch.Thumb para controlar el contenido del control deslizante. Root gestiona el estado y la apariencia de la pista; Thumb renderiza el contenido que proporcionas.
SwitchRootProps y SwitchThumbProps son tipos públicos exportados desde twenty-ui/primitives/input. Ambas partes aceptan atributos nativos, manejadores, refs, render y funciones de devolución de llamada de className y style basadas en el estado. La ref de Root apunta al control visible; inputRef apunta a la entrada nativa. 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 los estilos explícitos se combinan con los predeterminados. Thumb recibe el estado actual de checked, disabled, readOnly, required y Field. Su posición sigue la dirección de lectura. El ensamblaje invocable y su tipo SwitchProps siguen siendo compatibles. Reemplaza el ensamblaje con Root y su parte cuando proporciones contenido personalizado para el control deslizante, en lugar de añadir otra parte a los elementos secundarios del ensamblaje. Para restablecer un formulario controlado, gestiona el onReset del formulario y restaura checked a tu valor inicial. Base UI 1.8 no restaura el estado de los componentes no controlados al restablecer formularios de forma nativa. required, form, value y uncheckedValue conservan el comportamiento de la entrada nativa de origen.

”Props”

La referencia incluye props específicas del componente y props heredadas de Base UI. También se aceptan atributos nativos como aria-label y data-*.
boolean
Whether the switch is currently active.To render an uncontrolled switch, use the defaultChecked prop instead.
string | ((state: SwitchRootState) => 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 the switch is initially active.To render a controlled switch, 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 switch is rendered outside the form.
string
The id of the hidden input element.When nativeButton is true, the id is applied to the root element.
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 switch is activated or deactivated.
boolean
predeterminado:"false"
Whether the user should be unable to activate or deactivate the switch.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SwitchRootState>
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 activate the switch before submitting a form.
"md" | "sm"
predeterminado:"md"
Visual size of the switch.
CSSProperties | ((state: SwitchRootState) => 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 switch is off. By default, unchecked switches do not submit any value, matching native checkbox behavior.
string
The value submitted with the form when the switch is on. By default, switch submits the “on” value, matching native checkbox behavior.

Switch.Root

boolean
Whether the switch is currently active.To render an uncontrolled switch, use the defaultChecked prop instead.
string | ((state: SwitchRootState) => 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 the switch is initially active.To render a controlled switch, 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 switch is rendered outside the form.
string
The id of the hidden input element.When nativeButton is true, the id is applied to the root element.
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 switch is activated or deactivated.
boolean
predeterminado:"false"
Whether the user should be unable to activate or deactivate the switch.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SwitchRootState>
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 activate the switch before submitting a form.
"md" | "sm"
predeterminado:"md"
Visual size of the switch.
CSSProperties | ((state: SwitchRootState) => 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 switch is off. By default, unchecked switches do not submit any value, matching native checkbox behavior.
string
The value submitted with the form when the switch is on. By default, switch submits the “on” value, matching native checkbox behavior.

Switch.Thumb

string | ((state: SwitchThumbState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SwitchThumbState>
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: SwitchThumbState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.