QRCode

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:

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:

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 to change the background color. Keep a high contrast between the two colors so that the code stays scannable:

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:

Low (~7%)

Medium (~15%)

Quartile (~25%)

High (~30%)

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:

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:

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:

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:

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:

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:

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

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