> ## Documentation Index
> Fetch the complete documentation index at: https://docs.twenty.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Cambiar

> Un control etiquetado de encendido o apagado con estado controlado y no controlado.

## Resumen

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

**Light**

[Ejemplo de Cambiar (light)](https://storybook.twenty.com/iframe.html?id=ui-input-switch-switch--display\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Ejemplo de Cambiar (dark)](https://storybook.twenty.com/iframe.html?id=ui-input-switch-switch--display\&viewMode=story\&globals=colorScheme:dark)

[Open in Storybook](https://storybook.twenty.com/?path=/story/ui-input-switch-switch--display)

## Uso

### Estado no controlado

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

```tsx theme={null}
import { useId } from 'react';
import { Switch } from 'twenty-ui/primitives/input';
import { Text } from 'twenty-ui/primitives/typography';

export const NotificationsPreference = () => {
  const switchId = useId();

  return (
    <label
      htmlFor={switchId}
      style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}
    >
      <Switch id={switchId} name="notifications" />
      <Text render={<span />}>Email notifications</Text>
    </label>
  );
};
```

## 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.

**Light**

[Opciones visuales para el interruptor (light)](https://storybook.twenty.com/iframe.html?id=ui-input-switch-switch--catalog\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Opciones visuales para el interruptor (dark)](https://storybook.twenty.com/iframe.html?id=ui-input-switch-switch--catalog\&viewMode=story\&globals=colorScheme:dark)

[Open in Storybook](https://storybook.twenty.com/?path=/story/ui-input-switch-switch--catalog)

## Estado controlado

Pasa `checked` y actualízalo con `onCheckedChange` para controlar la misma preferencia en el estado de React.

```tsx theme={null}
import { useId, useState } from 'react';
import { Switch } from 'twenty-ui/primitives/input';
import { Text } from 'twenty-ui/primitives/typography';

export const NotificationsPreference = () => {
  const switchId = useId();
  const [checked, setChecked] = useState(false);

  return (
    <label
      htmlFor={switchId}
      style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}
    >
      <Switch
        id={switchId}
        name="notifications"
        checked={checked}
        onCheckedChange={setChecked}
      />
      <Text render={<span />}>Email notifications</Text>
    </label>
  );
};
```

`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](https://docs.twenty.com/es/ui/components/settings/settings-row.md).

## 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.

```tsx theme={null}
import { Switch } from 'twenty-ui/primitives/input';

export const CustomPreference = () => (
  <Switch.Root aria-label="Updates" defaultChecked>
    <Switch.Thumb></Switch.Thumb>
  </Switch.Root>
);
```

`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.

**Light**

[Composición de partes de Switch (light)](https://storybook.twenty.com/iframe.html?id=ui-input-switch-parts--composition\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Composición de partes de Switch (dark)](https://storybook.twenty.com/iframe.html?id=ui-input-switch-parts--composition\&viewMode=story\&globals=colorScheme:dark)

[Open in Storybook](https://storybook.twenty.com/?path=/story/ui-input-switch-parts--composition)

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-*`.

**checked** `boolean`

Whether the switch is currently active.

To render an uncontrolled switch, use the `defaultChecked` prop instead.

**className** `string | ((state: SwitchRootState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**defaultChecked** `boolean` (default: false)

Whether the switch is initially active.

To render a controlled switch, use the `checked` prop instead.

**disabled** `boolean` (default: false)

Whether the component should ignore user interaction.

**form** `string`

Identifies the form that owns the hidden input.
Useful when the switch is rendered outside the form.

**id** `string`

The id of the hidden input element.

When `nativeButton` is `true`, the id is applied to the root element.

**inputRef** `Ref\<HTMLInputElement\>`

A ref to access the hidden `<input>` element.

**name** `string`

Identifies the field when a form is submitted.

**nativeButton** `boolean` (default: 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.

**onCheckedChange** `((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.

**readOnly** `boolean` (default: false)

Whether the user should be unable to activate or deactivate the switch.

**render** `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.

**required** `boolean` (default: false)

Whether the user must activate the switch before submitting a form.

**size** `"md" | "sm"` (default: md)

Visual size of the switch.

**style** `CSSProperties | ((state: SwitchRootState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.

**uncheckedValue** `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.

**value** `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

**Root.checked** `boolean`

Whether the switch is currently active.

To render an uncontrolled switch, use the `defaultChecked` prop instead.

**Root.className** `string | ((state: SwitchRootState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**Root.defaultChecked** `boolean` (default: false)

Whether the switch is initially active.

To render a controlled switch, use the `checked` prop instead.

**Root.disabled** `boolean` (default: false)

Whether the component should ignore user interaction.

**Root.form** `string`

Identifies the form that owns the hidden input.
Useful when the switch is rendered outside the form.

**Root.id** `string`

The id of the hidden input element.

When `nativeButton` is `true`, the id is applied to the root element.

**Root.inputRef** `Ref\<HTMLInputElement\>`

A ref to access the hidden `<input>` element.

**Root.name** `string`

Identifies the field when a form is submitted.

**Root.nativeButton** `boolean` (default: 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.

**Root.onCheckedChange** `((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.

**Root.readOnly** `boolean` (default: false)

Whether the user should be unable to activate or deactivate the switch.

**Root.render** `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.

**Root.required** `boolean` (default: false)

Whether the user must activate the switch before submitting a form.

**Root.size** `"md" | "sm"` (default: md)

Visual size of the switch.

**Root.style** `CSSProperties | ((state: SwitchRootState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.

**Root.uncheckedValue** `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.

**Root.value** `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

**Thumb.className** `string | ((state: SwitchThumbState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**Thumb.render** `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.

**Thumb.style** `CSSProperties | ((state: SwitchThumbState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.