Saltar al contenido

Toggle Buttons

Los botones de alternancia se pueden utilizar para agrupar opciones relacionadas.

To emphasize groups of related Toggle buttons, a group should share a common container. The ToggleButtonGroup controls the selected state of its child buttons when given its own value prop.

Exclusive selection

With exclusive selection, selecting one option deselects any other.

In this example text justification toggle buttons present options for left, center, right, and fully justified text (disabled), with only one item available for selection at a time.

Selección múltiple

Multiple selection allows for logically-grouped options, like bold, italic, and underline, to have multiple options selected.

Tamaños

Botones más grandes o más pequeños? Usa la propiedad size.

Vertical buttons

The buttons can be stacked vertically with the orientation prop set to "vertical".

<ToggleButtonGroup
  orientation="vertical"
  value={view}
  exclusive
  onChange={handleChange}
>
  <ToggleButton value="list" aria-label="list">
    <ViewListIcon />
  </ToggleButton>
  <ToggleButton value="module" aria-label="module">
    <ViewModuleIcon />
  </ToggleButton>
  <ToggleButton value="quilt" aria-label="quilt">
    <ViewQuiltIcon />
  </ToggleButton>
</ToggleButtonGroup>

Forzar valor establecido

If you want to enforce that at least one button must be active, you can adapt your handleChange function.

const handleFormat = (event, newFormats) => {
  if (newFormats.length) {
    setFormats(newFormats);
  }
};

const handleAlignment = (event, newAlignment) => {
  if (newAlignment !== null) {
    setAlignment(newAlignment);
  }
};

Botón de conmutación independiente

<ToggleButton
  value="check"
  selected={selected}
  onChange={() => {
    setSelected(!selected);
  }}
>
  <CheckIcon />
</ToggleButton>

Botón de conmutación personalizado

He aquí un ejemplo de personalización del componente. Puedes aprender más sobre esto en la sección Personalizando Componentes de la documentación.


Accesibilidad

ARIA

  • ToggleButtonGroup has role="group". You should provide an accessible label with aria-label="label", aria-labelledby="id" or <label>.
  • ToggleButton sets aria-pressed="<bool>" according to the button state. You should label each button with aria-label.

Teclado

At present, toggle buttons are in DOM order. Navigate between them with the tab key. The button behavior follows standard keyboard semantics.