UIPackage React Native
Search

Qr Code

Scannable dark-on-light QR code with bounded size, spec quiet zone, and an encode-failure fallback.

Install

First install? Set up the registry in your app.

npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add qr-code

Source files

Expand a file to read the source the installer copies into your app.

components/ui/qr-code/QRCode.tsx
import * as React from 'react'
import { View, type ViewProps } from 'react-native'
import QRCodeSvg from 'react-native-qrcode-svg'
import { Text } from '@/components/ui/text'
import { renderTextChildren } from '@/lib/label-children'
import { cn } from '@/lib/utils'

/** Smaller boxes put modules under ~1dp for dense payloads; larger ones exceed tablet layouts. */
export const QR_CODE_MIN_SIZE = 96
export const QR_CODE_MAX_SIZE = 512
const DEFAULT_SIZE = 192

export type QRCodeErrorCorrection = 'L' | 'M' | 'Q' | 'H'

export interface QRCodeProps extends Omit<ViewProps, 'children'> {
  /** Payload to encode. Empty or over-capacity values render `fallback`. */
  value: string
  /** Outer box in dp, quiet zone included. Clamped to 96–512. */
  size?: number
  /** Error correction level; higher survives damage but needs more modules. */
  ecl?: QRCodeErrorCorrection
  /**
   * Light margin drawn inside `size`, in symbol units (the code spans `size` of
   * them, so the code shrinks as this grows). Defaults to `size * 4 / 21`: four
   * modules of the smallest (21-module) symbol, so every symbol version gets
   * at least the four-module quiet zone the QR spec requires. Pass 0 only when
   * the code already sits on a light surround of its own.
   */
  quietZone?: number
  /**
   * Modules and quiet zone stay dark-on-light in every theme: many scanners
   * cannot read inverted codes, so these are not theme tokens and do not flip
   * in dark mode. Keep at least the default contrast when overriding.
   */
  color?: string
  backgroundColor?: string
  /** Called once, after commit, when the value cannot be encoded. */
  onError?: (error: Error) => void
  /** Rendered inside the box when encoding fails. */
  fallback?: React.ReactNode
  className?: string
}

const clamp = (value: number | undefined, fallback: number, min: number, max: number) =>
  value !== undefined && Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : fallback

export const QRCode = React.forwardRef<React.ComponentRef<typeof View>, QRCodeProps>(
  (
    {
      value,
      size,
      ecl = 'M',
      quietZone,
      color = '#000000',
      backgroundColor = '#FFFFFF',
      onError,
      fallback = <Text variant="muted">QR code unavailable.</Text>,
      accessibilityLabel = 'QR code',
      className,
      style,
      ...props
    },
    ref,
  ) => {
    const box = clamp(size, DEFAULT_SIZE, QR_CODE_MIN_SIZE, QR_CODE_MAX_SIZE)
    const margin = clamp(quietZone, Math.ceil((box * 4) / 21), 0, Math.floor(box / 2))
    // The library encodes in useMemo([value, size, ecl]) and calls onError during its render.
    // Record the error in a ref there; report it and switch to the fallback from an effect.
    const key = `${ecl}:${box}:${value}`
    const pending = React.useRef<Error | null>(null)
    const [failedKey, setFailedKey] = React.useState<string | null>(null)
    const onErrorRef = React.useRef(onError)
    React.useEffect(() => {
      onErrorRef.current = onError
    })
    React.useEffect(() => {
      const error = pending.current
      pending.current = null
      if (!error) {
        setFailedKey(null)
        return
      }
      setFailedKey(key)
      onErrorRef.current?.(error)
    }, [key])
    const record = React.useCallback((error: unknown) => {
      pending.current = error instanceof Error ? error : new Error(String(error))
    }, [])
    const failed = failedKey === key

    return (
      <View
        {...props}
        ref={ref}
        accessible={!failed}
        accessibilityRole={failed ? undefined : 'image'}
        accessibilityLabel={failed ? undefined : accessibilityLabel}
        className={cn('items-center justify-center overflow-hidden', className)}
        style={[{ width: box, height: box }, style]}
      >
        {failed ? (
          renderTextChildren(fallback)
        ) : (
          <QRCodeSvg
            value={value}
            size={box}
            ecl={ecl}
            quietZone={margin}
            color={color}
            backgroundColor={backgroundColor}
            onError={record}
          />
        )}
      </View>
    )
  },
)
QRCode.displayName = 'QRCode'
components/ui/qr-code/index.ts
export * from './QRCode'

Dependencies

Registry items

npm packages

  • react-native-qrcode-svg
  • react-native-svg
Browse content and media