# Barcode

> Zero-dependency 1D barcodes (Code 39, Code 11, Codabar, Code 32, Code 93, Code 128, GS1-128, EAN, UPC, ITF-14) and Data Matrix as one SVG path, with text, bearer bars, colors, invalid-value handling and image export.

Canonical: https://salmonui.dev/docs/data-visualization/barcode

```tsx
import { Barcode, type BarcodeApi } from '@salmonui/charts/barcode';
import '@salmonui/charts/barcode/styles.css';

<Barcode type="ean13" value="590123412345" />;
```

`Barcode` and `QRCode` live in `@salmonui/charts/barcode`. The encoders are
pure functions in the package (no dependency, no `measureText`), so the
server renders the final symbol and the client markup is identical.

The stacked and dot symbologies are subpaths of their own, so a page pays
only for the encoder it uses; they share every option below and the barcode
stylesheet:

| Component | Import | Page |
| --- | --- | --- |
| `Gs1DataBar` | `@salmonui/charts/barcode/gs1-databar` | [GS1 DataBar](https://salmonui.dev/docs/data-visualization/gs1-databar) |
| `Pdf417` | `@salmonui/charts/barcode/pdf417` | [PDF417](https://salmonui.dev/docs/data-visualization/pdf417) |
| `DotCode` | `@salmonui/charts/barcode/dotcode` | [DotCode](https://salmonui.dev/docs/data-visualization/dotcode) |

## Symbologies

| `type` | Data | Notes |
| --- | --- | --- |
| `code39`, `code39Extended` | Code 39 set; Extended: ASCII 0 to 127 | `checksum` adds the mod-43 check character |
| `code11`, `codabar`, `code32`, `code93`, `code93Extended` | digits and `-`; Codabar with A to D start and stop; Code 32: 8 digits; Code 93 set or ASCII | Code 11 C and K checks, Code 32 check digit and base-32 encoding, Code 93 C and K checks |
| `code128` | ASCII 0 to 127 | Optimal automatic code set switching; `codeSet: 'a' \| 'b' \| 'c'` forces one |
| `ean8`, `ean13`, `upcA`, `upcE` | 7 / 12 / 11 / 6 digits, check digit optional | The check digit is computed when omitted and validated when given |
| `gs1Code128`, `itf14` | `(01)09501101530003(10)ABC`; 13 or 14 digits | GS1 application identifiers with FNC1 after variable-length fields |
| `dataMatrix` | ISO 8859-1 text | See [Data Matrix](https://salmonui.dev/docs/data-visualization/data-matrix) |

## Text and layout

- `text`: `true` (default) shows the encoded value (EAN and UPC in their
  guard-separated groups), a string replaces it, `false` hides it;
  `textPosition: 'top' | 'bottom'`; `textAlign: 'start' | 'center' | 'end'`.
  The font is the system font.
- `moduleSize` (narrow bar width, default 2 px; 4 px for Data Matrix) or
  `width` / `height`; the quiet zone is kept unless `quietZone={false}`.
- `bearerBar: 'frame' | 'horizontal' | 'none'`, default `'frame'` for
  `itf14`.
- `color` / `background` are data colors (default black on white in both
  color schemes, because scanners need a dark symbol on a light background);
  development builds warn below 3:1 contrast.

## Invalid values

A value the symbology cannot encode never throws: the component renders an
empty `role="img"` whose name is the reason (`invalidLabel` customizes it) and
calls `onInvalid({ reason })`. Without `onInvalid`, development builds
log a warning instead.

```tsx
<Barcode type="ean13" value={input} onInvalid={({ reason }) => setError(reason)} />
```

### Live demo: Barcode encoder and validation

Live demo: https://salmonui.dev/demos/data-visualization/barcode-encoder

Code 11, Codabar, Code 32, Code 93 and Code 93 Extended from a text field with onInvalid reasons, plus a Data Matrix with selectable encodation and symbol size and GS1 element strings in Data Matrix and QR Code.

`Demo.tsx`:

```tsx
'use client';

import { useCallback, useState } from 'react';
import { Select } from '@salmonui/dropdowns/select';
import { TextField } from '@salmonui/inputs/text-field';
import { Barcode, QRCode, type BarcodeDataMatrixEncoding, type BarcodeInvalidEvent } from '@salmonui/charts/barcode';

const cell = { display: 'grid', gap: 4, justifyItems: 'start' } as const;

type LinearType = 'code11' | 'codabar' | 'code32' | 'code93' | 'code93Extended';
const LINEAR: readonly { type: LinearType; name: string; sample: string }[] = [
  { type: 'code11', name: 'Code 11', sample: '123-45' },
  { type: 'codabar', name: 'Codabar', sample: 'A40156B' },
  { type: 'code32', name: 'Code 32 (Italian pharmacode)', sample: '01234567' },
  { type: 'code93', name: 'Code 93', sample: 'SALMON-93' },
  { type: 'code93Extended', name: 'Code 93 Extended', sample: 'Salmon 93!' },
];
const SIZES = ['auto', 'auto-rectangular', '16x16', '20x20', '24x24', '8x32', '12x36', '16x48'];
const ENCODINGS: readonly BarcodeDataMatrixEncoding[] = ['auto', 'ascii', 'asciiNumeric', 'base256'];
const PRESETS = {
  gs1: { name: 'GS1: GTIN, expiry and lot', value: '(01)09501101530003(17)261231(10)LOT-42' },
  digits: { name: 'Serial number (digits)', value: '4006381333931' },
  text: { name: 'Text with symbols', value: 'Lot #42 · exp. 2026-12-31' },
} as const;
type Preset = keyof typeof PRESETS;

/** Type a value into any symbology: invalid input reports its reason instead of throwing. */
export default function BarcodeEncoderDemo() {
  const [type, setType] = useState<LinearType>('code93');
  const [value, setValue] = useState('SALMON-93');
  const [invalid, setInvalid] = useState<{ key: string; reason: string } | null>(null);
  const [encoding, setEncoding] = useState<BarcodeDataMatrixEncoding>('auto');
  const [size, setSize] = useState('auto');
  const [preset, setPreset] = useState<Preset>('gs1');
  const [dmInvalid, setDmInvalid] = useState<{ key: string; reason: string } | null>(null);
  const key = `${type}:${value}`;
  const dmKey = `${preset}:${encoding}:${size}`;
  // Stable handlers: onInvalid runs after commit whenever the reason changes.
  const onInvalid = useCallback((e: BarcodeInvalidEvent) => setInvalid({ key, reason: e.reason }), [key]);
  const onDmInvalid = useCallback((e: BarcodeInvalidEvent) => setDmInvalid({ key: dmKey, reason: e.reason }), [dmKey]);
  const dmValue = PRESETS[preset].value;
  return (
    <div className="demo-stack">
      <p>
        <strong>Linear symbologies</strong>
      </p>
      <div className="demo-toolbar" role="group" aria-label="Linear barcode">
        <label>
          Symbology
          <Select
            aria-label="Symbology"
            data={LINEAR.map((l) => ({ value: l.type, label: l.name }))}
            value={type}
            onValueChange={(selected) => {
              const next = LINEAR.find((l) => l.type === selected) ?? LINEAR[0]!;
              setType(next.type);
              setValue(next.sample);
            }}
          />
        </label>
        <label>
          Value
          <TextField aria-label="Value" value={value} onValueChange={setValue} />
        </label>
      </div>
      <Barcode type={type} value={value} onInvalid={onInvalid} invalidLabel="Cannot encode: {reason}" />
      <p className="demo-status" aria-live="polite">
        {invalid?.key === key ? (
          <>
            onInvalid: <code>{invalid.reason}</code>
          </>
        ) : (
          'Valid value. Try letters in Code 11 or Code 32, or a lowercase letter in Code 93.'
        )}
      </p>

      <p>
        <strong>Data Matrix and GS1</strong>
      </p>
      <div className="demo-toolbar" role="group" aria-label="Data Matrix options">
        <label>
          Content
          <Select aria-label="Content" data={(Object.keys(PRESETS) as Preset[]).map((p) => ({ value: p, label: PRESETS[p].name }))} value={preset} onValueChange={(next) => next != null && setPreset(next as Preset)} />
        </label>
        <label>
          Encodation
          <Select aria-label="Encodation" data={ENCODINGS.map((enc) => ({ value: enc, label: enc }))} value={encoding} onValueChange={(next) => next != null && setEncoding(next as BarcodeDataMatrixEncoding)} />
        </label>
        <label>
          Symbol size
          <Select aria-label="Symbol size" data={SIZES.map((s) => ({ value: s, label: s }))} value={size} onValueChange={(next) => next != null && setSize(String(next))} />
        </label>
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 24, alignItems: 'flex-start' }}>
        <div style={cell}>
          <span>Data Matrix ECC 200</span>
          <Barcode type="dataMatrix" value={dmValue} gs1={preset === 'gs1'} encoding={encoding} size={size} moduleSize={4} onInvalid={onDmInvalid} />
        </div>
        <div style={cell}>
          <span>QR Code</span>
          <QRCode value={dmValue} gs1={preset === 'gs1'} moduleSize={3} />
        </div>
      </div>
      <p className="demo-status" aria-live="polite">
        Encoded: <code>{dmValue}</code>
        {dmInvalid?.key === dmKey ? (
          <>
            {' '}
            · Data Matrix onInvalid: <code>{dmInvalid.reason}</code>
          </>
        ) : null}
      </p>
    </div>
  );
}
```

## Accessibility, RTL and output

The symbol is one `<svg role="img">` whose accessible name defaults to the
value (`label` overrides it), drawn as one path of merged module runs with
`shape-rendering="crispEdges"`. Symbols never mirror in right-to-left
pages. Barcodes are static images: they have no keyboard interaction and no
tab stop.

The encoders run during render as pure functions, so server rendering
(Next.js App Router, Vite SSR) produces the final symbol and hydration
changes nothing; the export code loads lazily on first use.

`ref` gives a `BarcodeApi` with `element`, `toSVGString()` (also without a
DOM), `toBlob(format)`, `toDataURL(format)` and `export({ format, fileName,
scale })` for PNG, JPEG or SVG:

```tsx
const barcode = useRef<BarcodeApi>(null);

<Barcode ref={barcode} type="code128" value="SALMON-42" />;
// later
await barcode.current?.export({ format: 'png', fileName: 'label.png' });
```

## SVG only

SVG is the only renderer; there is no render-mode prop. A barcode
is a few hundred rectangles, and SVG is crisp at every scale, prints well and
renders on the server, so a canvas mode would add code without a speed
benefit. When you need a raster image, call `api.toBlob('png')` or
`api.toDataURL('png')`.

All props and types are in the
[API reference](https://salmonui.dev/docs/reference/charts/barcode).

### Live demo: Barcode symbologies

Live demo: https://salmonui.dev/demos/data-visualization/barcode-types

Code 128, EAN-13, UPC-E, ITF-14 with bearer bars, Code 39 with its check character, GS1-128 and a Data Matrix symbol, each drawn as one SVG path.

`Demo.tsx`:

```tsx
'use client';

import { Barcode } from '@salmonui/charts/barcode';

const cell = { display: 'grid', gap: 4, justifyItems: 'start' } as const;

// One symbol per family of symbologies.
export default function BarcodeTypesDemo() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 24 }}>
      <div style={cell}>
        <span>Code 128</span>
        <Barcode type="code128" value="SALMON-0042" />
      </div>
      <div style={cell}>
        <span>EAN-13</span>
        <Barcode type="ean13" value="590123412345" />
      </div>
      <div style={cell}>
        <span>UPC-E</span>
        <Barcode type="upcE" value="0123456" />
      </div>
      <div style={cell}>
        <span>ITF-14 with bearer bars</span>
        <Barcode type="itf14" value="1540014128876" moduleSize={1.5} />
      </div>
      <div style={cell}>
        <span>Code 39 with a check character</span>
        <Barcode type="code39" value="SALMON" checksum textAlign="start" />
      </div>
      <div style={cell}>
        <span>GS1-128</span>
        <Barcode type="gs1Code128" value="(01)09501101530003(10)AB-123" moduleSize={1.5} />
      </div>
      <div style={cell}>
        <span>Data Matrix</span>
        <Barcode type="dataMatrix" value="https://salmonui.dev" moduleSize={4} />
      </div>
    </div>
  );
}
```
