Saltar al contenido

🎉 Material UI v5 is out! Head to the migration guide to get started.

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

Text justification toggle buttons present options for left, right, center, full, and justified text with only one item available for selection at a time. Selecting one option deselects any other.

Selección múltiple

Logically-grouped options, like bold, italic, and underline, allow multiple options to be selected.

<ToggleButtonGroup value={formats} onChange={handleFormat} aria-label="text formatting">
  <ToggleButton value="bold" aria-label="bold">
    <FormatBoldIcon />
  </ToggleButton>
  <ToggleButton value="italic" aria-label="italic">
    <FormatItalicIcon />
  </ToggleButton>
  <ToggleButton value="underlined" aria-label="underlined">
    <FormatUnderlinedIcon />
  </ToggleButton>
  <ToggleButton value="color" aria-label="color" disabled>
    <FormatColorFillIcon />
    <ArrowDropDownIcon />
  </ToggleButton>
</ToggleButtonGroup>

Tamaños

Botones más grandes o más pequeños? Use the size prop.

Vertical buttons

<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 at least one button to 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. You can learn more about this in the overrides documentation page.


Accesibilidad

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