ComponentsToggleButton

ToggleButton

ToggleButton component represents a button that can be toggled on or off.

Documentation

Usage

ToggleButton extends the Button component.

import type { ComponentPropsWithRef } from "react";
 
import { ToggleButton } from "@optiaxiom/react";
import { IconLayoutSidebar } from "@tabler/icons-react";
 
export function App({
  size = "md",
}: Pick<ComponentPropsWithRef<typeof ToggleButton>, "size">) {
  return (
    <ToggleButton
      aria-label="Toggle sidebar"
      icon={<IconLayoutSidebar />}
      size={size}
    />
  );
}

Controlled

Use the pressed and defaultPressed props to toggle between controlled and uncontrolled usage. And combine it with onPressedChange to listen for changes to the state.

import { Button, Flex, ToggleButton } from "@optiaxiom/react";
import { IconLayoutSidebar } from "@tabler/icons-react";
import { useState } from "react";
 
export function App() {
  const [value, setValue] = useState(false);
 
  return (
    <Flex flexDirection="row">
      <ToggleButton
        aria-label="Toggle sidebar"
        icon={<IconLayoutSidebar />}
        onPressedChange={setValue}
        pressed={value}
      />
 
      <Button disabled={!value} onClick={() => setValue(false)}>
        Reset
      </Button>
    </Flex>
  );
}

Disabled state

Set the disabled prop to true to disable buttons and prevent any interactions.

For accessibility please make sure to include text that explains why the button is disabled or use a tooltip.

import { ToggleButton, Tooltip } from "@optiaxiom/react";
import { IconLayoutSidebar } from "@tabler/icons-react";
 
export function App() {
  return (
    <Tooltip content="Disabled toggle demo">
      <ToggleButton
        aria-label="Toggle sidebar"
        disabled
        icon={<IconLayoutSidebar />}
      />
    </Tooltip>
  );
}

Props

ToggleButton

Supports all Button props in addition to its own.

Name

Type

asChild

false | true

defaultPressed

false | true

The state of the toggle when initially rendered. Use defaultPressed if you do not need to control the state of the toggle. @defaultValue false

onPressedChange

(pressed: boolean) => void

The callback that fires when the state of the toggle changes.

pressed

false | true

The controlled state of the toggle.

Changelog

0.1.0

  • Added component

Copyright 2024 © Optimizely.