# QRCode
Package: @mantine/core
Import: import { QRCode } from '@mantine/core';
Description: Generate and display QR codes

## Usage

`QRCode` encodes a string into a QR code and renders it as an SVG. It has no external
dependencies and works with server-side rendering:

```tsx
import { QRCode } from '@mantine/core';

function Demo() {
  return <QRCode value="https://mantine.dev" />;
}
```


## Size

Set `size` prop to change the width and height of the code:

```tsx
import { Group, QRCode } from '@mantine/core';

function Demo() {
  return (
    <Group>
      <QRCode value="https://mantine.dev" size={100} />
      <QRCode value="https://mantine.dev" size={160} />
      <QRCode value="https://mantine.dev" size={240} />
    </Group>
  );
}
```


## Colors

Use `color` prop to change the color of the dark modules and
[bg style prop](https://alpha.mantine.dev/llms/styles-style-props.md) to change the background color.
Keep a high contrast between the two colors so that the code stays scannable:

```tsx
import { Group, QRCode } from '@mantine/core';

function Demo() {
  return (
    <Group>
      <QRCode value="https://mantine.dev" color="blue.8" bg="blue.0" />
      <QRCode value="https://mantine.dev" color="var(--mantine-color-grape-9)" />
    </Group>
  );
}
```


## Error correction level

`errorCorrectionLevel` prop controls how much of the code can be damaged or covered
while remaining readable, from `L` (about 7%) to `H` (about 30%). Higher levels produce
a denser code:

```tsx
import { QRCode, Stack, Text } from '@mantine/core';

const levels = [
  { level: 'L', label: 'Low (~7%)' },
  { level: 'M', label: 'Medium (~15%)' },
  { level: 'Q', label: 'Quartile (~25%)' },
  { level: 'H', label: 'High (~30%)' },
] as const;

function Demo() {
  return (
    <Stack>
      {levels.map(({ level, label }) => (
        <Stack key={level} align="center" gap="xs">
          <QRCode value="https://mantine.dev" errorCorrectionLevel={level} size={120} />
          <Text size="sm">{label}</Text>
        </Stack>
      ))}
    </Stack>
  );
}
```


## Capacity

A QR code holds from about 1270 bytes with `errorCorrectionLevel="H"` to about 2950 bytes
with `"L"`. When the value is longer, `QRCode` renders an empty code. Use `encodeQR` to
validate user input, it throws when the value does not fit:

```tsx
import { encodeQR } from '@mantine/core';

function canEncode(value: string) {
  try {
    encodeQR(value, { errorCorrectionLevel: 'H' });
    return true;
  } catch {
    return false;
  }
}
```

## Logo

Pass any React node to the `logo` prop to display it in the center of the code.
The logo covers a part of the code, set `errorCorrectionLevel="H"` to keep it scannable:

```tsx
import { QRCode } from '@mantine/core';
import { MantineLogo } from '@mantinex/mantine-logo';

function Demo() {
  return (
    <QRCode
      value="https://mantine.dev"
      size={240}
      errorCorrectionLevel="H"
      logo={<MantineLogo type="mark" style={{ width: '100%', height: '100%' }} />}
    />
  );
}
```


## Custom rendering with encodeQR

To fully control the appearance, for example to render rounded dots or export to canvas,
use `encodeQR` function to get the module matrix and render it yourself:

```tsx
import { encodeQR } from '@mantine/core';

const { matrix, size } = encodeQR('https://mantine.dev', { errorCorrectionLevel: 'M' });
// matrix – boolean[][], `true` for dark modules
// size – number of modules per side (without the quiet zone)
```

The three large squares in the corners and the alignment patterns must stay solid squares,
other modules can have any shape:

```tsx
import { encodeQR } from '@mantine/core';

const MARGIN = 4;

interface Pattern {
  x: number;
  y: number;
  n: number;
}

function getAlignmentPositions(size: number) {
  const version = (size - 17) / 4;
  if (version === 1) {
    return [];
  }
  const count = Math.floor(version / 7) + 2;
  const step = version === 32 ? 26 : Math.ceil((version * 4 + 4) / (count * 2 - 2)) * 2;
  const positions = [6];
  for (let pos = size - 7; positions.length < count; pos -= step) {
    positions.splice(1, 0, pos);
  }
  return positions;
}

function getPatterns(size: number): Pattern[] {
  const finders = [
    { x: 0, y: 0, n: 7 },
    { x: size - 7, y: 0, n: 7 },
    { x: 0, y: size - 7, n: 7 },
  ];
  const positions = getAlignmentPositions(size);
  const last = positions.length - 1;
  const alignments = positions.flatMap((cy, i) =>
    positions
      .filter(
        (_, j) => !(i === 0 && j === 0) && !(i === 0 && j === last) && !(i === last && j === 0)
      )
      .map((cx) => ({ x: cx - 2, y: cy - 2, n: 5 }))
  );
  return [...finders, ...alignments];
}

function getPatternPath({ x, y, n }: Pattern) {
  return [0, 1, 2]
    .map((i) => `M${x + MARGIN + i} ${y + MARGIN + i}h${n - i * 2}v${n - i * 2}h${i * 2 - n}z`)
    .join(' ');
}

function Demo() {
  const value = 'https://mantine.dev';
  const { matrix, size } = encodeQR(value, { errorCorrectionLevel: 'M' });
  const total = size + MARGIN * 2;
  const color = 'var(--mantine-color-blue-6)';
  const patterns = getPatterns(size);
  const isPatternModule = (x: number, y: number) =>
    patterns.some((p) => x >= p.x && x < p.x + p.n && y >= p.y && y < p.y + p.n);

  return (
    <svg viewBox={`0 0 ${total} ${total}`} width={180} height={180} role="img" aria-label={value}>
      <rect width={total} height={total} fill="white" />
      <path d={patterns.map(getPatternPath).join(' ')} fill={color} fillRule="evenodd" />
      {matrix.flatMap((row, y) =>
        row.map((dark, x) =>
          dark && !isPatternModule(x, y) ? (
            <circle
              key={`${x}-${y}`}
              cx={x + MARGIN + 0.5}
              cy={y + MARGIN + 0.5}
              r={0.42}
              fill={color}
            />
          ) : null
        )
      )}
    </svg>
  );
}
```


## Accessibility

By default, `aria-label` of the code is the encoded `value`. Set `aria-label`
or `aria-labelledby` prop to provide a more descriptive name:

```tsx
import { QRCode } from '@mantine/core';

function Demo() {
  return <QRCode value="https://mantine.dev" aria-label="Link to mantine.dev" />;
}
```

To hide a decorative code that is duplicated by nearby text, use `attributes` prop
of the [Styles API](https://alpha.mantine.dev/llms/styles-styles-api.md):

```tsx
import { QRCode } from '@mantine/core';

function Demo() {
  return (
    <QRCode
      value="https://mantine.dev"
      attributes={{ svg: { 'aria-hidden': true } }}
    />
  );
}
```


#### Props

**QRCode props**

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| color | MantineColor | - | Color of the dark modules, key of `theme.colors` or any valid CSS color value, `var(--mantine-color-black)` by default |
| errorCorrectionLevel | QRCodeErrorCorrectionLevel | - | Error correction level, higher levels keep the code scannable when it is partially damaged or covered by a logo, `'M'` by default |
| logo | React.ReactNode | - | Content rendered as a centered overlay, usually a logo. Pair with `errorCorrectionLevel="H"` to keep the code scannable |
| margin | number | - | Quiet zone width around the code in modules, `4` (specification minimum) by default |
| size | string \| number | - | Width and height of the QR code, numbers are converted to rem, `160` by default |
| value | string | required | Value encoded into the QR code |


#### Styles API

QRCode component supports Styles API. With Styles API, you can customize styles of any inner element. Follow the documentation to learn how to use CSS modules, CSS variables and inline styles to get full control over component styles.

**QRCode selectors**

| Selector | Static selector | Description |
|----------|----------------|-------------|
| root | .mantine-QRCode-root | Root element |
| svg | .mantine-QRCode-svg | Inner `svg` element that renders the QR code modules |
| logo | .mantine-QRCode-logo | Centered overlay element that wraps the `logo` prop content |

**QRCode CSS variables**

| Selector | Variable | Description |
|----------|----------|-------------|
| root | --qr-size | Controls `width` and `height` of the root element |
| root | --qr-color | Controls the color of the dark modules |
