# Button

> A native button with tones, variants, sizes, icons, icon-only metrics, press-and-hold repeat and a render prop for links, plus the rules every Buttons component shares.

Canonical: https://salmonui.dev/docs/buttons/button

```tsx
import { Button } from '@salmonui/buttons/button';
import '@salmonui/buttons/button/styles.css';

<Button tone="primary" onClick={save}>Save</Button>;
```

`Button` renders a native `<button>` (APG Button). It is stateless: there is
nothing to control, and its events are the native ones (`onClick`, `onFocus`,
...) plus `onRepeat`; the pressed state lives on
[ToggleButton](https://salmonui.dev/docs/buttons/toggle-button). Its label is `children`, any
React node; HTML strings are never rendered. `ref` points at
the `<button>`, so `ref.current.focus()` and `ref.current.click()` cover
imperative focus and activation; there are no component methods.

## Tones, variants and sizes

- `tone`: `'neutral'` (default), `'primary'`,
  `'success'`, `'warning'`, `'danger'`, `'info'`. The five
  non-neutral tones are the theme seeds; there is no other color input.
- `variant`: `'solid'` (default), `'outline'`, `'ghost'`,
  `'link'` and `'chip'` (see
  [Chips](https://salmonui.dev/docs/buttons/chips)). Every tone and variant pair meets 4.5:1 text
  contrast in light and dark.
- `size`: `'sm'`, `'md'` (default), `'lg'`. It picks one of three
  fixed metric sets (24, 32 or 40 px tall), and the theme's
  `density: 'compact'` tightens each of them by 4 px (see
  [Density](https://salmonui.dev/docs/data-grid/appearance#density)); use `size="lg"` for
  larger touch targets.

Every state is a `data-*` styling hook on `.salmon-button`: `data-variant`,
`data-tone`, `data-size`, `data-icon-only`, `data-loading`, `data-pressed`,
`data-floating`. Keyboard focus shows a `:focus-visible` ring from the
theme's focus color; `:hover` and `:active` change the fill.

### Live demo: Button tones, variants and sizes

Live demo: https://salmonui.dev/demos/buttons/button-basics

Every tone and variant (the contrast matrix), the three sizes, icons, an icon-only button with its name and tooltip, a disabled button, keyboard activation and a link rendered through `render`.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button, type ButtonTone, type ButtonVariant } from '@salmonui/buttons/button';

const TONES: ButtonTone[] = ['neutral', 'primary', 'success', 'warning', 'danger', 'info'];
const VARIANTS: ButtonVariant[] = ['solid', 'outline', 'ghost', 'link'];

const PlusIcon = () => (
  <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
    <path d="M8 3v10M3 8h10" />
  </svg>
);

// Tones x variants, sizes, icons, an icon-only button and a link rendered through `render`.
export default function ButtonBasicsDemo() {
  const [clicks, setClicks] = useState(0);
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      {VARIANTS.map((variant) => (
        <div key={variant} style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {TONES.map((tone) => (
            <Button key={tone} tone={tone} variant={variant}>
              {tone}
            </Button>
          ))}
        </div>
      ))}
      <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 8 }}>
        <Button size="sm">Small</Button>
        <Button>Medium</Button>
        <Button size="lg">Large</Button>
        <Button tone="primary" iconStart={<PlusIcon />} onClick={() => setClicks((n) => n + 1)}>
          Add ({clicks})
        </Button>
        <Button iconOnly aria-label="Add" title="Add" iconStart={<PlusIcon />} onClick={() => setClicks((n) => n + 1)} />
        <Button disabled>Disabled</Button>
        <Button variant="link" render={(props) => <a {...props} href="#demo-button-basics-title" />}>
          A link styled as a button
        </Button>
      </div>
    </div>
  );
}
```

## Icons and icon-only buttons

`iconStart` and `iconEnd` take any React node and render it as a decorative
(`aria-hidden`) part before or after the label. They are logical: in a
`dir="rtl"` container `iconStart` sits on the right. Icon
classes and fonts are not used.

`iconOnly` gives square metrics. Its props type then requires `aria-label` or
`aria-labelledby`, and a development warning names the button when both are
missing at runtime.

```tsx
<Button iconOnly aria-label="Delete" iconStart={<TrashIcon />} tone="danger" variant="ghost" />
```

## Press and hold

`repeat` turns on press-and-hold repeat. The first activation is the
native `onClick`; each repeat while the button is held calls
`onRepeat({ count, source })`. `repeat.delay` (default 400 ms) is the
hold time before the first repeat and `repeat.interval` (default 100 ms) the
time between repeats; a held Space or Enter repeats on the same timer, and
operating system key repeats are ignored. Timers live in refs and
stop on release, pointer leave, `pointercancel`, key up and blur.

### Live demo: Press and hold to repeat

Live demo: https://salmonui.dev/demos/buttons/button-repeat

A quantity stepper whose buttons repeat while held, with the default 400 ms delay and a custom delay and interval.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button, ButtonGroup } from '@salmonui/buttons/button';

const Icon = ({ d }: { readonly d: string }) => (
  <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
    <path d={d} />
  </svg>
);

// Press and hold: the first activation is onClick, every repeat is onRepeat.
export default function ButtonRepeatDemo() {
  const [value, setValue] = useState(10);
  const step = (delta: number) => setValue((v) => Math.max(0, Math.min(100, v + delta)));
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <ButtonGroup aria-label="Quantity" variant="outline">
        <Button aria-label="Decrease" iconOnly iconStart={<Icon d="M3 8h10" />} repeat onClick={() => step(-1)} onRepeat={() => step(-1)} />
        <Button aria-label="Increase" iconOnly iconStart={<Icon d="M8 3v10M3 8h10" />} repeat={{ delay: 300, interval: 60 }} onClick={() => step(1)} onRepeat={() => step(1)} />
      </ButtonGroup>
      <output aria-live="polite">Quantity: {value}</output>
    </div>
  );
}
```

## Keyboard, forms and links

- Enter and Space activate, Tab moves focus: native `<button>` behavior.
Holding the key repeats when `repeat` is set.
- `type` defaults to `"button"`, so a button inside a form never submits by
  accident; pass `type="submit"` or `type="reset"` explicitly.
  `name`, `value`, `form` and `formAction` pass through.
- `disabled` is the native attribute, so `<fieldset disabled>` disables the
  button too.
- `render` swaps the element: it receives every computed prop (class
  names, `data-*`, ARIA, handlers, `ref`, children) and must spread them. On a
  non-button element `disabled` becomes `aria-disabled="true"` with an inert
  click handler; an element that is neither a link nor a button gets
  `role="button"`, `tabIndex={0}` and Enter / Space activation.

```tsx
<Button variant="link" render={(props) => <Link {...props} to="/orders" />}>Orders</Button>
```

- `title` passes through as the tooltip; a Tooltip component belongs
  to a later category.

## Shared rules

- `className` is appended after `salmon-button` and `style` is merged;
  every other DOM prop (`id`, `aria-*`, `data-*`, event handlers) goes to the
  `<button>`. Built-in handlers run after yours and are skipped when yours
  calls `event.preventDefault()`.
- State is controlled through props; the components never write storage.
There are no lifecycle events or teardown methods:
  use effects.
- Built-in strings are props with English defaults: `loadingLabel` and
  `progressLabel` here, `menuLabel` on the split button.
- Motion is one fixed CSS transition, off under `prefers-reduced-motion`; there
  is no ripple and no animation API. Theming is one theme
  with five seeds and a color scheme.
- Every component renders on the server and hydrates without warnings.
axe-core is clean in light, dark and RTL and the ARIA is native
  `<button>` semantics.

### Live demo: Button attributes, classes and server rendering

Live demo: https://salmonui.dev/demos/buttons/button-attributes

className and style on a Button, DOM attributes passed through to the native button, a handler that vetoes the built-in toggle with preventDefault, and a status that shows the demo was rendered on the server and then hydrated.

`Demo.tsx`:

```tsx
'use client';

import { useState, useSyncExternalStore } from 'react';
import { Button, ToggleButton } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';

const noopSubscribe = () => () => {};

// className / style passthrough, DOM attributes, handler composition and an
// SSR status: the server snapshot says "server HTML", the client "hydrated".
export default function ButtonAttributesDemo() {
  const hydrated = useSyncExternalStore(
    noopSubscribe,
    () => true,
    () => false,
  );
  const [locked, setLocked] = useState(false);
  const [pinned, setPinned] = useState(false);
  const [archived, setArchived] = useState(0);
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 8 }}>
        <Button
          className="demo-archive-button"
          style={{ minInlineSize: 140, letterSpacing: '0.02em' }}
          data-analytics-id="archive"
          aria-describedby="demo-button-attributes-hint"
          onClick={() => setArchived((n) => n + 1)}
        >
          Archive ({archived})
        </Button>
        <ToggleButton
          pressed={pinned}
          onPressedChange={setPinned}
          onClick={(event) => {
            if (locked) event.preventDefault();
          }}
        >
          {pinned ? 'Pinned' : 'Pin'}
        </ToggleButton>
        <Checkbox checked={locked} onCheckedChange={(checked) => setLocked(checked)}>
          Lock pin
        </Checkbox>
      </div>
      <p id="demo-button-attributes-hint" style={{ margin: 0 }}>Archived items stay searchable for 30 days.</p>
      <p style={{ margin: 0 }}>
        Rendering: <output>{hydrated ? 'hydrated' : 'server HTML'}</output>
      </p>
    </div>
  );
}
```

## Not included

- No shape props: round and rounded-corner buttons are not offered; radius
  is system-owned and `floating` buttons are circular.
- No full-width prop: use `style={{ width: '100%' }}`.
- No icon above or below the label; compose the stack inside `children`.
- `type` defaults to `"button"`, not the HTML `"submit"`.

## Performance budgets

The Buttons families are gated by `npm run bundle:check` and their browser
and SSR specs: `@salmonui/buttons/button` is at most 3.5 KB
gzip (`Button` alone 1.55 KB) and never pulls menu, overlay or positioning
code; the Menu family is at most 9.6 KB; `@salmonui/buttons/tag-group` loads
4.15 KB first and its drag code only on the first drag. A toggle paints
within 16 ms, an arrow key in a 50-item `ToggleButtonGroup` or a 1,000-item
menu within 8 ms, and 100 `Button`s render on the server in under 5 ms; a
closed `MenuButton` renders the same markup whatever its item count.
Extracting the shared primitives kept every Data Grid budget unchanged;
the grid keeps its smaller private menu code instead of the
general primitives. The [long menu demo](https://salmonui.dev/docs/buttons/menu-button#performance)
shows the open time of a 1,000-item menu on your machine, and the demo below
runs the SSR measurement in your browser.

### Live demo: Server rendering cost

Live demo: https://salmonui.dev/demos/buttons/button-ssr-cost

Runs React's renderToString in the browser over 100 Buttons and a closed MenuButton with 100 and 1,000 items, showing the time per render and that the closed menu's markup does not grow with its items.

`Demo.tsx`:

```tsx
'use client';

import { useState, type CSSProperties } from 'react';
import { Button } from '@salmonui/buttons/button';
import { MenuButton, type MenuItemData } from '@salmonui/buttons/menu';

interface Result {
  readonly buttonsMs: number;
  readonly menu100Ms: number;
  readonly menu1000Ms: number;
  readonly menu100Length: number;
  readonly menu1000Length: number;
}

const items = (count: number): MenuItemData[] => Array.from({ length: count }, (_, index) => ({ id: `item-${index}`, label: `Item ${index + 1}` }));

// A compact label / value readout: labels in the secondary text color, values below.
const DL: CSSProperties = { display: 'grid', gap: 2, margin: 0 };
const DT: CSSProperties = { color: 'var(--salmon-text-secondary)' };
const DD: CSSProperties = { margin: '0 0 8px' };

function timed(render: () => string, runs = 5): { ms: number; html: string } {
  let html = render(); // warm-up
  const start = performance.now();
  for (let run = 0; run < runs; run++) html = render();
  return { ms: (performance.now() - start) / runs, html };
}

// Runs React's renderToString in the browser (loaded on demand) over the same
// trees the SSR budgets measure: 100 Buttons, and a closed MenuButton with
// 100 and 1,000 items whose markup does not depend on the item count.
export default function ButtonSsrCostDemo() {
  const [result, setResult] = useState<Result | null>(null);
  const [running, setRunning] = useState(false);
  const run = async () => {
    setRunning(true);
    const { renderToString } = await import('react-dom/server');
    const hundred = Array.from({ length: 100 }, (_, index) => index);
    const buttons = timed(() =>
      renderToString(
        <div>
          {hundred.map((index) => (
            <Button key={index} tone={index % 2 ? 'primary' : 'neutral'}>
              Button {index + 1}
            </Button>
          ))}
        </div>,
      ),
    );
    const list100 = items(100);
    const list1000 = items(1000);
    const menu100 = timed(() => renderToString(<MenuButton items={list100}>Actions</MenuButton>));
    const menu1000 = timed(() => renderToString(<MenuButton items={list1000}>Actions</MenuButton>));
    setResult({ buttonsMs: buttons.ms, menu100Ms: menu100.ms, menu1000Ms: menu1000.ms, menu100Length: menu100.html.length, menu1000Length: menu1000.html.length });
    setRunning(false);
  };
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <div>
        <Button tone="primary" loading={running} loadingLabel="Measuring" onClick={run}>
          Measure server rendering
        </Button>
      </div>
      {result ? (
        <dl style={DL}>
          <dt style={DT}>100 Buttons, renderToString</dt>
          <dd style={DD}>{result.buttonsMs.toFixed(2)} ms (budget 5 ms in Node)</dd>
          <dt style={DT}>Closed MenuButton, 100 items</dt>
          <dd style={DD}>
            {result.menu100Ms.toFixed(2)} ms, {result.menu100Length} characters
          </dd>
          <dt style={DT}>Closed MenuButton, 1,000 items</dt>
          <dd style={DD}>
            {result.menu1000Ms.toFixed(2)} ms, {result.menu1000Length} characters (budget 2 ms in Node)
          </dd>
          <dt style={DT}>Same markup for 100 and 1,000 items</dt>
          <dd style={DD}>{String(result.menu100Length === result.menu1000Length)}</dd>
        </dl>
      ) : (
        <p style={{ margin: 0 }}>Press the button to run the measurement in this browser.</p>
      )}
    </div>
  );
}
```

## API reference

[`@salmonui/buttons/button`](https://salmonui.dev/docs/reference/buttons/button): `Button`,
`ToggleButton`, `ButtonGroup`, `ToggleButtonGroup` and their types
(`ButtonProps`, `ButtonTone`, `ButtonVariant`, `ButtonSize`,
`ButtonFloatingPosition`, `ButtonRepeatOptions`, `ButtonRepeatEvent`,
`ButtonRenderProps`).
