### Install qrcode.react
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/QUICK_START.md
Install the qrcode.react library using npm, yarn, or pnpm. Requires React 16.8+.
```bash
npm install qrcode.react
# or
yarn add qrcode.react
# or
pnpm add qrcode.react
```
--------------------------------
### Install qrcode.react
Source: https://github.com/zpao/qrcode.react/blob/trunk/README.md
Install the qrcode.react library using npm. This command adds the package to your project's dependencies.
```sh
npm install qrcode.react
```
--------------------------------
### QrSegment.makeSegments Examples
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
Demonstrates the output of `makeSegments` for different input string types, showing automatic mode detection.
```typescript
QrSegment.makeSegments('123') // → [numeric segment]
QrSegment.makeSegments('ABC123') // → [alphanumeric segment]
QrSegment.makeSegments('hello') // → [byte segment]
QrSegment.makeSegments('123abc') // → [byte segment] (mixed)
```
--------------------------------
### Webpack Configuration for qrcode.react
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/EXPORT_STRUCTURE.md
Example webpack configuration for a project using qrcode.react. Ensure ts-loader is installed and configured for TypeScript files.
```javascript
import {QRCodeSVG} from 'qrcode.react';
export default {
entry: './src/index.tsx',
output: {filename: 'bundle.js'},
module: {
rules: [{
test: /\.tsx?$/,
loader: 'ts-loader'
}]
},
resolve: {extensions: ['.ts', '.tsx']}
};
```
--------------------------------
### Tree-Shaking Example: Using QRCodeSVG
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/EXPORT_STRUCTURE.md
Demonstrates how bundlers can tree-shake unused components like QRCodeCanvas when only QRCodeSVG is imported. This optimizes bundle size.
```typescript
import {QRCodeSVG} from 'qrcode.react';
// Final bundle: ~12KB gzipped instead of ~7KB
```
--------------------------------
### Tree-Shaking Example: Using QRCodeCanvas
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/EXPORT_STRUCTURE.md
Illustrates that importing QRCodeCanvas also results in a similar bundle size increase, as the core qrcodegen logic is shared. Bundlers will still optimize by removing unused exports.
```typescript
import { QRCodeCanvas} from 'qrcode.react';
// Final bundle: ~12KB gzipped instead of ~7KB
// (qrcodegen is shared between both, so each adds ~5KB, total still ~7KB)
```
--------------------------------
### Implement Responsive QR Code Sizing
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/configuration.md
Use the `size` prop for responsive QR code designs, not CSS scaling. This example demonstrates dynamically updating the QR code size based on window dimensions.
```javascript
// Use size prop for responsive designs, not CSS scaling
const [qrSize, setQrSize] = useState(256);
useEffect(() => {
const updateSize = () => {
const width = Math.min(window.innerWidth - 40, 512);
setQrSize(width);
};
updateSize();
window.addEventListener('resize', updateSize);
return () => window.removeEventListener('resize', updateSize);
}, []);
return ;
```
--------------------------------
### QR Code Segment Optimization Example
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
Illustrates how using segment optimization with `qrcode.react` can significantly reduce the QR code size compared to using byte mode for mixed character types.
```typescript
// Instead of:
value="123456ABC" // 8 bytes × 8 bits = 64 bits (byte mode)
// Use:
value={['123456', 'ABC']} // 6 digits × 3.33 + 3 chars × 5.5 ≈ 36 bits
// Saves ~44% space through segment optimization
```
--------------------------------
### Responsive QRCodeSVG
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/QUICK_START.md
Make the QR code responsive by dynamically adjusting its size based on the window dimensions. This example uses `useState` and `useEffect` hooks to manage the size.
```typescript
import {useState, useEffect} from 'react';
import {QRCodeSVG} from 'qrcode.react';
export function ResponsiveQR() {
const [size, setSize] = useState(256);
useEffect(() => {
const resize = () => {
setSize(Math.min(window.innerWidth - 40, 512));
};
resize();
window.addEventListener('resize', resize);
return () => window.removeEventListener('resize', resize);
}, []);
return ;
```
--------------------------------
### Accessing Canvas with useRef for Download
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/QRCodeCanvas.md
Demonstrates how to use `useRef` to get a reference to the canvas element. This allows for advanced interactions like downloading the QR code as a PNG image.
```javascript
import {QRCodeCanvas} from 'qrcode.react';
import {useRef} from 'react';
function MyComponent() {
const canvasRef = useRef(null);
const handleDownload = () => {
const canvas = canvasRef.current;
if (canvas) {
const url = canvas.toDataURL('image/png');
const a = document.createElement('a');
a.href = url;
a.download = 'qrcode.png';
a.click();
}
};
return (
<>
>
);
}
```
--------------------------------
### Accessible QR Code in React
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/QUICK_START.md
This example demonstrates how to make a QR code accessible by providing a title, ARIA label, and role. This helps screen readers and other assistive technologies to interpret the QR code's purpose.
```typescript
```
--------------------------------
### Download QRCodeCanvas as PNG File
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/QUICK_START.md
Enable downloading the QR code as a PNG image using the QRCodeCanvas component. The canvas element's `toDataURL` method is used to get the image data.
```typescript
import {useRef} from 'react';
import {QRCodeCanvas} from 'qrcode.react';
export function DownloadPNG() {
const canvasRef = useRef(null);
const download = () => {
const canvas = canvasRef.current;
if (!canvas) return;
const url = canvas.toDataURL('image/png');
const a = document.createElement('a');
a.href = url;
a.download = 'qrcode.png';
a.click();
};
return (
<>
>
);
}
```
--------------------------------
### qrcode.react Usage of encodeSegments
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
Example demonstrating how qrcode.react utilizes the encodeSegments method for creating QR codes from various input values, handling segment creation and error correction levels.
```typescript
const values = Array.isArray(value) ? value : [value];
const segments = values.reduce((accum, v) => {
accum.push(...qrcodegen.QrSegment.makeSegments(v));
return accum;
}, []);
const qrcode = qrcodegen.QrCode.encodeSegments(
segments,
ERROR_LEVEL_MAP[level], // 'L' → Ecc.LOW, etc.
minVersion,
undefined, // maxVersion = 40 (default)
undefined, // mask = -1 (automatic)
boostLevel // true (default)
);
```
--------------------------------
### Forwarding Refs to QR Code Components
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/README.md
Forward refs to QRCodeSVG and QRCodeCanvas components to get direct DOM access. Ensure you import `useRef` from React.
```typescript
import {useRef} from 'react';
import {QRCodeSVG} from 'qrcode.react';
const svgRef = useRef(null);
const canvasRef = useRef(null);
```
--------------------------------
### Basic QRCode Component
Source: https://github.com/zpao/qrcode.react/blob/trunk/examples/index.html
Shows the basic usage of the QRCode component. Ensure the component is imported correctly.
```html
Output
```
--------------------------------
### Architecture Overview
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/README.md
Illustrates the data flow and component hierarchy for QR code generation within the React application.
```text
QRCodeSVG / QRCodeCanvas
↓
useQRCode() hook
↓
qrcodegen.QrCode.encodeSegments()
↓
qrcodegen library (bundled)
↓
SVG/Canvas rendering
```
--------------------------------
### QR Code with Embedded Logo
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/README.md
Adds a logo to the center of the QR code. The 'excavate' option removes a portion of the QR code to make space for the logo. This example uses QRCodeSVG.
```typescript
```
--------------------------------
### Importing QRCodeCanvas Component
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/EXPORT_STRUCTURE.md
Demonstrates how to import the QRCodeCanvas component and its associated types.
```typescript
// Default import style
import {QRCodeCanvas} from 'qrcode.react';
// With type import
import {QRCodeCanvas} from 'qrcode.react';
import type {ComponentProps} from 'react';
type Props = ComponentProps;
```
--------------------------------
### useQRCode Memoization Dependencies
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/Hooks.md
Illustrates the two levels of memoization used within the useQRCode hook: QR code encoding and rendering calculations. These memos help optimize performance by caching results.
```typescript
// First memo: QR code encoding
const qrcode = React.useMemo(() => {
// Segments creation and encoding
}, [value, level, minVersion, boostLevel])
// Second memo: Rendering calculations
const {cells, margin, numCells, calculatedImageSettings} = React.useMemo(() => {
// Module extraction and image calculations
}, [qrcode, size, imageSettings, includeMargin, marginSize])
```
--------------------------------
### Responsive Container Styling
Source: https://github.com/zpao/qrcode.react/blob/trunk/examples/index.html
CSS for the container to manage layout of the QRCode component and other elements. Adapts to screen size.
```css
.container {
display: flex;
justify-content: center;
gap: 1rem;
}
.output {
margin-left: 1rem;
}
@media only screen and (max-width: 600px) {
.container {
flex-direction: column;
}
}
```
--------------------------------
### Importing QRCodeSVG Component
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/EXPORT_STRUCTURE.md
Demonstrates how to import the QRCodeSVG component and its associated types.
```typescript
// Default import style
import {QRCodeSVG} from 'qrcode.react';
// With type import
import {QRCodeSVG} from 'qrcode.react';
import type {ComponentProps} from 'react';
type Props = ComponentProps;
```
--------------------------------
### Module Formats
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/README.md
Demonstrates importing the QRCodeSVG component using different module formats (ESM, CJS).
```typescript
import {QRCodeSVG} from 'qrcode.react'
```
```javascript
const {QRCodeSVG} = require('qrcode.react')
```
--------------------------------
### Type-Safe QR Code Wrapper in React with TypeScript
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/QUICK_START.md
This example illustrates how to create a type-safe wrapper component for QRCodeSVG using TypeScript. It extracts the props type and defines a new interface to add custom props like 'label', ensuring better type checking and developer experience.
```typescript
import {QRCodeSVG} from 'qrcode.react';
import type {ComponentProps} from 'react';
// Extract props type
type QRCodeProps = ComponentProps;
// Create typed wrapper
interface MyQRProps extends QRCodeProps {
label?: string;
}
export function MyQR({label, ...props}: MyQRProps) {
return (
{label &&
{label}
}
);
}
// Usage
```
--------------------------------
### QrSegment.makeBytes
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
Creates a byte mode segment from raw binary data.
```APIDOC
## QrSegment.makeBytes
### Description
Creates a byte mode segment from binary data.
### Method
`static makeBytes(data: Readonly>): QrSegment`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript
const binaryData = [0x01, 0x02, 0x03];
const byteSegment = QrSegment.makeBytes(binaryData);
```
### Response
#### Success Response
- **QrSegment** - A QrSegment object in byte mode.
```
--------------------------------
### getModules Instance Method (Extended API)
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
Returns the complete 2D module grid of the QR code. This extended API is used by qrcode.react for rendering purposes.
```typescript
getModules(): Array>
```
--------------------------------
### getModule Instance Method
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
Retrieves the color of a specific module at given coordinates within the QR code grid. Returns false for out-of-bounds coordinates.
```typescript
getModule(x: int, y: int): boolean
```
--------------------------------
### Package.json Configuration for Exports
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/EXPORT_STRUCTURE.md
Defines the main, module, types, and conditional exports for different module systems and environments.
```json
{
"main": "./lib/index.js",
"module": "./lib/esm/index.js",
"types": "./lib/index.d.ts",
"exports": {
".": {
"import": {
"types": "./lib/index.d.mts",
"default": "./lib/esm/index.js"
},
"require": {
"types": "./lib/index.d.ts",
"default": "./lib/index.js"
}
}
}
}
```
--------------------------------
### Tsup Build Command for qrcode.react
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/EXPORT_STRUCTURE.md
Command used to build the source TypeScript files into different module formats (ESM, CJS) and generate type declarations.
```bash
tsup src/index.tsx -d lib --format esm,cjs --dts --legacy-output --target=es2017 --platform=browser
```
--------------------------------
### Vite Configuration for qrcode.react
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/EXPORT_STRUCTURE.md
A simple React component using qrcode.react within a Vite project. No special configuration is typically needed for Vite.
```typescript
import {QRCodeSVG} from 'qrcode.react';
export function App() {
return ;
}
```
--------------------------------
### Basic QRCodeSVG Usage
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/QRCodeSVG.md
Renders a basic QR code for a given URL. Ensure the 'qrcode.react' library is imported.
```javascript
import {QRCodeSVG} from 'qrcode.react';
function MyApp() {
return (
);
}
```
--------------------------------
### QRCodeSVG Component Usage
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/QRCodeSVG.md
Demonstrates how to use the QRCodeSVG component with basic and advanced props.
```APIDOC
## QRCodeSVG Component
### Description
The `QRCodeSVG` component renders a QR code as a scalable vector graphics (SVG) element. SVG is the recommended rendering method as it provides superior flexibility, scalability, and performance across various use cases.
### Component Signature
```typescript
const QRCodeSVG = React.forwardRef(
function QRCodeSVG(props, forwardedRef)
): React.ReactElement
```
### Props
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| value | `string | string[]` | Yes | — | The data to encode in the QR code. Can be a single string or an array of strings for optimized multi-segment encoding. |
| size | `number` | No | `128` | The rendered size of the QR code in pixels. Applies to both width and height. |
| level | `'L' | 'M' | 'Q' | 'H'` | No | `'L'` | Error correction level. Higher levels add redundancy: L (~7%), M (~15%), Q (~25%), H (~30%). |
| bgColor | `string` | No | `'#FFFFFF'` | Background color as a CSS color value. Applied to the light modules. |
| fgColor | `string` | No | `'#000000'` | Foreground color as a CSS color value. Applied to the dark modules. |
| marginSize | `number` | No | `0` | Number of modules to render as margin. Follows QR specification (4) or custom values. Floored to integer. |
| includeMargin | `boolean` | No | `false` | **Deprecated.** Use `marginSize` instead. When true, adds a 4-module margin. |
| title | `string` | No | — | Accessibility title for the SVG element. Rendered as a `` child element. |
| minVersion | `number` | No | `1` | Minimum QR code version (1-40). Version determines QR code complexity and data capacity. |
| boostLevel | `boolean` | No | `true` | If true, error correction level may be increased if data fits without increasing version. |
| imageSettings | `ImageSettings` | No | — | Configuration for embedding a logo/image into the QR code. See ImageSettings type. |
| ...svgAttributes | `React.SVGAttributes` | No | — | Pass-through SVG attributes like `style`, `className`, `aria-label`, etc. |
### Example Usage
```jsx
import QRCodeSVG from 'qrcode.react';
function App() {
return (
);
}
```
```
--------------------------------
### Constants
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
Defines the minimum and maximum supported versions for QR code generation.
```APIDOC
## Constants
```typescript
QrCode.MIN_VERSION = 1;
QrCode.MAX_VERSION = 40;
```
```
--------------------------------
### QrSegment.makeBytes Factory Method
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
Creates a byte mode segment from binary data. Use this when dealing with raw byte arrays.
```typescript
static makeBytes(data: Readonly>): QrSegment
```
--------------------------------
### Import Components
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/README.md
Import the main SVG and Canvas components from the library.
```typescript
import {QRCodeSVG, QRCodeCanvas} from 'qrcode.react';
```
--------------------------------
### Peer Dependencies for qrcode.react
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/EXPORT_STRUCTURE.md
Specifies the required React versions for the qrcode.react library. Ensure your project meets these version requirements.
```json
{
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
}
```
--------------------------------
### getImageSettings
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/Hooks.md
Calculates the actual image dimensions and positioning based on QR code metrics and user-provided settings. It handles scaling, centering, and excavation region calculation for embedded images.
```APIDOC
## getImageSettings
### Description
Calculates actual image dimensions and positioning based on QR code metrics and user-provided settings. It converts pixel dimensions to module-based coordinates, applies scaling, and handles positioning and excavation calculation.
### Parameters
- **cells** (Modules): The module grid.
- **size** (number): The rendered QR code size in pixels.
- **margin** (number): The margin size in modules.
- **imageSettings** (ImageSettings, optional): User-provided image configuration.
### Returns
- An object containing calculated image metrics (`x`, `y`, `h`, `w`, `excavation`, `opacity`, `crossOrigin`), or `null` if no settings are provided.
### Scaling Logic
- Converts pixel dimensions to module-based coordinates.
- Applies scale factor: `scale = numCells / size` (modules per pixel).
- Default image size: `10% of QR code size` if not specified.
### Positioning
- If x/y not specified: centers image.
- If x/y specified: positions relative to QR code origin.
### Excavation Calculation
- If `excavate: true`: creates an excavation region.
- Floors x/y, ceils width/height to align with module boundaries.
```
--------------------------------
### Basic QR Code Generation with QRCodeSVG
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/START_HERE.md
Renders a QR code using the QRCodeSVG component. Import the component and provide the 'value' prop with the data to encode. Customization options like 'size' and 'level' are available.
```typescript
// Import
import {QRCodeSVG} from 'qrcode.react';
// Use
// That's it! Full QR code rendered.
```
--------------------------------
### QR Code Version and Capacity Reference
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
Provides a reference table for QR code versions, their corresponding grid sizes, and data capacity in bytes for different error correction levels (L, M, Q, H).
```plaintext
| Version | Grid Size | Capacity (L) | Capacity (M) | Capacity (Q) | Capacity (H) |
|---------|-----------|---|---|---|---|
| 1 | 21×21 | 17 | 14 | 11 | 7 |
| 5 | 37×37 | 128 | 106 | 86 | 65 |
| 10 | 57×57 | 346 | 271 | 207 | 144 |
| 20 | 97×97 | 958 | 753 | 574 | 399 |
| 40 | 177×177 | 2953 | 2331 | 1663 | 1273 |
(Capacity in bytes for byte mode)
```
--------------------------------
### Version and Capacity Reference
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
A reference table mapping QR code versions to their corresponding grid sizes and data capacities for different error correction levels (L, M, Q, H). Capacities are shown in bytes for byte mode.
```APIDOC
## Version and Capacity Reference
| Version | Grid Size | Capacity (L) | Capacity (M) | Capacity (Q) | Capacity (H) |
|---------|-----------|---|---|---|---|
| 1 | 21×21 | 17 | 14 | 11 | 7 |
| 5 | 37×37 | 128 | 106 | 86 | 65 |
| 10 | 57×57 | 346 | 271 | 207 | 144 |
| 20 | 97×97 | 958 | 753 | 574 | 399 |
| 40 | 177×177 | 2953 | 2331 | 1663 | 1273 |
(Capacity in bytes for byte mode)
```
--------------------------------
### Responsive QR Code with High-DPI Support
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/QRCodeCanvas.md
Creates a responsive QR code that adjusts its size based on the window width. It uses `useState` and `useEffect` to manage the size and listen for window resize events.
```javascript
import {QRCodeCanvas} from 'qrcode.react';
import {useState, useEffect} from 'react';
function ResponsiveQRCode() {
const [size, setSize] = useState(256);
useEffect(() => {
const handleResize = () => {
const width = Math.min(window.innerWidth - 40, 512);
setSize(width);
};
window.addEventListener('resize', handleResize);
handleResize();
return () => window.removeEventListener('resize', handleResize);
}, []);
return (
);
}
```
--------------------------------
### QrCode.getModules
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
Returns the complete 2D module grid representing the QR code, where each element indicates if a module is dark (true) or light (false). This is an extended API added by qrcode.react.
```APIDOC
## QrCode.getModules
### Description
Returns the complete module grid for rendering.
### Method
`instance`
### Returns
2D array where `modules[y][x]` is `true` for dark, `false` for light
### Note
Extended API (added by qrcode.react). Used by qrcode.react rendering functions.
```
--------------------------------
### Set Minimum QR Code Version
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/configuration.md
Use `minVersion` to specify the smallest QR code version that can be used. The library will automatically select the smallest version that fits the data, respecting this lower bound.
```javascript
```
--------------------------------
### Import Types
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/README.md
Import types for error correction levels and image settings, and component props.
```typescript
import type {
ErrorCorrectionLevel,
ImageSettings,
} from 'qrcode.react';
// Via ComponentProps for full prop type
import type {ComponentProps} from 'react';
type QRCodeProps = ComponentProps;
```
--------------------------------
### Download QRCodeSVG as SVG File
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/QUICK_START.md
Implement functionality to download the generated QR code as an SVG file. This involves serializing the SVG element to a string and creating a Blob for download.
```typescript
import {useRef} from 'react';
import {QRCodeSVG} from 'qrcode.react';
export function DownloadSVG() {
const svgRef = useRef(null);
const download = () => {
const svg = svgRef.current;
if (!svg) return;
const serializer = new XMLSerializer();
const svgStr = serializer.serializeToString(svg);
const blob = new Blob([svgStr], {type: 'image/svg+xml'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'qrcode.svg';
a.click();
URL.revokeObjectURL(url);
};
return (
<>
>
);
}
```
--------------------------------
### Basic QR Code Rendering
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/QRCodeCanvas.md
Renders a basic QR code for a given URL using the QRCodeCanvas component. Ensure the 'qrcode.react' library is imported.
```javascript
import {QRCodeCanvas} from 'qrcode.react';
function MyApp() {
return (
);
}
```
--------------------------------
### QrCode.getModule
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
Retrieves the color of a specific module at given coordinates (x, y). Returns false for out-of-bounds coordinates.
```APIDOC
## QrCode.getModule
### Description
Returns the color of the module at coordinates.
### Method
`instance`
### Parameters
- **x** (int) - Required - Coordinates (0-indexed from top-left)
- **y** (int) - Required - Coordinates (0-indexed from top-left)
### Returns
`true` for dark module, `false` for light module
### Behavior
Returns `false` if coordinates out of bounds
```
--------------------------------
### Default Rendering Parameters
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/Hooks.md
Defines default values for QR code size, error correction level, background and foreground colors, margin inclusion, minimum version, and image scale.
```typescript
const DEFAULT_SIZE = 128;
const DEFAULT_LEVEL: ErrorCorrectionLevel = 'L';
const DEFAULT_BGCOLOR = '#FFFFFF';
const DEFAULT_FGCOLOR = '#000000';
const DEFAULT_INCLUDEMARGIN = false;
const DEFAULT_MINVERSION = 1;
const DEFAULT_IMG_SCALE = 0.1; // 10% of QR code size
```
--------------------------------
### Set Background and Foreground Colors
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/configuration.md
Customize the QR code's appearance using 'bgColor' for the background and 'fgColor' for the foreground modules. Any valid CSS color string is accepted, including hex, RGB, RGBA, and named colors.
```javascript
```
--------------------------------
### QrCode Class Reference
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/00_MANIFEST.txt
Reference for the QrCode class, detailing its factory methods, error correction levels (enum), segment encoding, and version capacity.
```APIDOC
## QrCode Class
### Description
Provides a reference for the `QrCode` class, which is the core library for generating QR code data. It documents factory methods, the `QrCode.Ecc` enum for error correction levels, `QrSegment` for data encoding, and version capacity details.
### Method
Class
### Endpoint
N/A (Class API)
### Parameters
#### Class Methods
- **QrCode.generate(text, options)**: Factory method to create a QR code instance.
- **text** (string) - The data to encode.
- **options** (object) - Configuration options for QR code generation.
- **level** (string) - Error correction level ('L', 'M', 'Q', 'H').
- **size** (number) - The desired size of the QR code matrix.
- **encoding** (string) - The encoding mode (e.g., 'numeric', 'alphanumeric', 'byte', 'kanji').
#### Enums
- **QrCode.Ecc**: Enum for error correction levels.
- **L**: Low (7% correction)
- **M**: Medium (15% correction)
- **Q**: Quartile (25% correction)
- **H**: High (30% correction)
#### Types
- **QrSegment**: Represents a segment of encoded data.
- **Data Types**: Various constants and types related to data encoding and QR code structure.
### Request Example
```javascript
import { QrCode } from 'qrcode-generator';
const qrCodeInstance = QrCode.generate('Some data', {
level: 'M',
size: 2,
encoding: 'alphanumeric'
});
// Accessing segments, version, etc. from qrCodeInstance
```
### Response
#### Success Response (200)
- Returns a `QrCode` instance containing the generated QR code data.
#### Response Example
```json
{
"version": 1,
"segments": [...],
"eccLevel": "M",
"mask": 7
}
```
```
--------------------------------
### Define ImageSettings Type
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/types.md
Defines the configuration for embedding a logo or image into the QR code. Position and opacity have default values.
```typescript
type ImageSettings = {
src: string;
height: number;
width: number;
excavate: boolean;
x?: number;
y?: number;
opacity?: number;
crossOrigin?: CrossOrigin;
}
```
--------------------------------
### Common Props for QR Code Components
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/START_HERE.md
Configure QR code appearance and data using common props like value, size, level, bgColor, and fgColor.
```typescript
```
--------------------------------
### Calculate Image Settings for QR Code Overlay
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/Hooks.md
Calculates the precise dimensions, position, and excavation region for an image to be overlaid on a QR code. It handles scaling based on QR code size and user-defined settings, centering or positioning the image as needed. Use this to ensure an image integrates correctly without obscuring QR code data.
```typescript
function getImageSettings(
cells: Modules,
size: number,
margin: number,
imageSettings?: ImageSettings
): null | {
x: number;
y: number;
h: number;
w: number;
excavation: Excavation | null;
opacity: number;
crossOrigin: CrossOrigin;
}
```
--------------------------------
### excavateModules
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/Hooks.md
Creates a copy of the module grid with a specified rectangular region cleared (set to false/light). This is useful for clearing QR code modules behind embedded images to improve contrast.
```APIDOC
## excavateModules
### Description
Creates a copy of the module grid with a rectangular region cleared (set to false/light). This function is used for clearing QR code modules behind embedded images to improve contrast.
### Parameters
- **modules** (Modules): The original module grid.
- **excavation** (Excavation): An object with `{x, y, w, h}` defining the region to clear.
### Returns
- A new module grid with the specified excavation applied.
### Usage
Used for clearing QR code modules behind embedded images to improve contrast.
```
--------------------------------
### Set QR Code Size
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/configuration.md
The 'size' prop controls the rendered width and height of the QR code in pixels. Recommended sizes vary based on the intended use case, from small embedded codes to large printouts.
```javascript
```
--------------------------------
### Basic QR Code Generation
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/README.md
Generates a basic QR code for a given value using the QRCodeSVG component. Ensure QRCodeSVG is imported.
```typescript
import {QRCodeSVG} from 'qrcode.react';
```
--------------------------------
### Generate Optimized SVG Path for QR Code Modules
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/Hooks.md
Generates an optimized SVG path string for the dark modules of a QR code. It groups consecutive dark modules into single 'move' and 'horizontal line' commands for minimal SVG syntax. Use this for rendering the foreground of the QR code efficiently.
```typescript
function generatePath(modules: Modules, margin: number = 0): string
```
```text
M5 0h2v1H5zM8 0h3v1H8zM5 1h2v1H5z...
```
--------------------------------
### Exporting Primary Components
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/EXPORT_STRUCTURE.md
Exports the main QRCodeCanvas and QRCodeSVG components from the package.
```typescript
export {QRCodeCanvas, QRCodeSVG};
```
--------------------------------
### Next.js (App Router) Component with qrcode.react
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/EXPORT_STRUCTURE.md
A client component for Next.js App Router that renders a QR code. It requires the 'use client' directive.
```typescript
'use client';
import {QRCodeSVG} from 'qrcode.react';
export function MyQRCode({value}: {value: string}) {
return ;
}
```
--------------------------------
### Generate Printable QR Code in React
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/QUICK_START.md
This snippet shows how to create a QR code that can be printed. It uses a ref to capture the SVG element and a button to trigger the print functionality, opening a new window with the QR code for printing.
```typescript
import {useRef} from 'react';
import {QRCodeSVG} from 'qrcode.react';
export function PrintableQR() {
const qrRef = useRef(null);
const print = () => {
const printWindow = window.open('', '_blank');
if (!printWindow || !qrRef.current) return;
const serializer = new XMLSerializer();
const svgStr = serializer.serializeToString(qrRef.current);
printWindow.document.write(
"\n \n QR Code\n ${svgStr}\n "
);
printWindow.document.close();
printWindow.print();
};
return (
<>
>
);
}
```
--------------------------------
### Basic SVG QR Code
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/QUICK_START.md
Render a QR code as an SVG element. This is the recommended method for most use cases.
```typescript
import {QRCodeSVG} from 'qrcode.react';
export function MyComponent() {
return ;
}
```
--------------------------------
### Render QR Code with SVG
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/START_HERE.md
Use QRCodeSVG for rendering QR codes. It requires the 'value' prop for the data to be encoded.
```typescript
import {QRCodeSVG} from 'qrcode.react';
```
--------------------------------
### Render QR Code as Canvas
Source: https://github.com/zpao/qrcode.react/blob/trunk/README.md
Use the QRCodeCanvas component to render a QR code for a given URL. This component may be preferable in certain scenarios.
```javascript
import ReactDOM from 'react-dom';
import {QRCodeCanvas} from 'qrcode.react';
ReactDOM.render(
,
document.getElementById('mountNode')
);
```
--------------------------------
### generatePath
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/Hooks.md
Generates an optimized SVG path string for the dark modules of a QR code. It iterates through the module grid, grouping consecutive dark modules to create minimal SVG path commands, reducing DOM nodes compared to individual rectangles.
```APIDOC
## generatePath
### Description
Generates an optimized SVG path string representing dark modules in the QR code. It iterates through the module grid horizontally, grouping consecutive dark modules into single M (move) and h (horizontal line) commands for minimal SVG path syntax.
### Parameters
- **modules** (Modules): 2D array from `qrcode.getModules()`
- **margin** (number, optional): Offset to add to all coordinates. Defaults to 0.
### Returns
- SVG path string ready for the `` attribute.
### Example Output
```
M5 0h2v1H5zM8 0h3v1H8zM5 1h2v1H5z...
```
```
--------------------------------
### QRCodeCanvas Component Reference
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/00_MANIFEST.txt
Detailed documentation for the QRCodeCanvas component, covering its props, rendering details, and support for high-DPI displays. This component is used for pixel-based QR code rendering.
```APIDOC
## QRCodeCanvas
### Description
Provides a complete reference for the `QRCodeCanvas` component, which renders QR codes using a canvas element for pixel-based output. It details props, `ImageSettings`, canvas rendering specifics, and high-DPI support.
### Method
Component
### Endpoint
N/A (Component API)
### Parameters
#### Props Reference
- **value** (string) - Required - The data to encode in the QR code.
- **size** (number) - Optional - The size of the QR code in pixels.
- **level** (string) - Optional - The error correction level (e.g., 'L', 'M', 'Q', 'H').
- **bgColor** (string) - Optional - The background color of the QR code.
- **fgColor** (string) - Optional - The foreground color of the QR code.
- **includeMargin** (boolean) - Optional - Whether to include a margin around the QR code.
- **imageSettings** (object) - Optional - Settings for embedding an image in the center of the QR code.
- **src** (string) - Required - The source URL of the image.
- **width** (number) - Required - The width of the image.
- **height** (number) - Required - The height of the image.
- **excavate** (boolean) - Optional - Whether to excavate the QR code around the image.
- **renderAs** (string) - Optional - Specifies the rendering mode ('svg' or 'canvas'). Defaults to 'svg'.
- **id** (string) - Optional - The ID attribute for the canvas element.
- **className** (string) - Optional - The class attribute for the canvas element.
- **style** (object) - Optional - The style attribute for the canvas element.
- **title** (string) - Optional - The title attribute for the canvas element.
- **ariaLabel** (string) - Optional - The aria-label attribute for accessibility.
- **canvasStyle** (object) - Optional - Inline styles for the canvas element.
### Request Example
```jsx
```
### Response
#### Success Response (200)
- Renders a canvas element representing the QR code.
#### Response Example
```html
```
```
--------------------------------
### QrCode Class Definition
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
Defines the QrCode class structure, including its properties and static factory methods for encoding QR codes.
```typescript
export class QrCode {
readonly version: int;
readonly size: int;
readonly mask: int;
readonly errorCorrectionLevel: QrCode.Ecc;
// Factory methods
static encodeText(text: string, ecl: QrCode.Ecc): QrCode
static encodeBinary(data: Readonly>, ecl: QrCode.Ecc): QrCode
static encodeSegments(
segs: Readonly>,
ecl: QrCode.Ecc,
minVersion?: int,
maxVersion?: int,
mask?: int,
boostEcl?: boolean
): QrCode
// Accessor methods
getModule(x: int, y: int): boolean
getModules(): Array>
}
```
--------------------------------
### QrCode.encodeText
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
High-level API for creating a QR code from text. Automatically detects optimal encoding mode and selects the smallest version. Note: Doesn't allow segment optimization. Use encodeSegments() for multi-segment encoding.
```APIDOC
## QrCode.encodeText
### Description
High-level API for creating a QR code from text. Automatically detects optimal encoding mode and selects the smallest version.
### Method
`static`
### Parameters
- **text** (string) - Required - Unicode string to encode (up to 738 characters for low error correction)
- **ecl** (QrCode.Ecc) - Required - Error correction level
### Returns
QrCode instance
### Note
High-level API; doesn't allow segment optimization. Use `encodeSegments()` for multi-segment encoding.
```
--------------------------------
### Error Handling
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
Details the conditions under which the library throws `RangeError` and how errors are handled by the qrcode.react component.
```APIDOC
## Error Handling
### RangeError Conditions
The library throws `RangeError` in these conditions:
| Condition | Method | Example |
|-----------|--------|---------|
| Invalid version range | encodeSegments | `minVersion > maxVersion` |
| Invalid mask | encodeSegments | `mask < -1 or mask > 7` |
| Data too long | encodeSegments | Payload exceeds maxVersion capacity |
| Invalid segment | makeNumeric/makeAlphanumeric | Input contains disallowed characters |
| Invalid ECI value | makeEci | `assignVal < 0` |
**qrcode.react handling:** Errors from qrcodegen are not caught; they propagate as uncaught exceptions. Ensure valid props to avoid errors.
```
--------------------------------
### QrSegment.makeSegments
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/api-reference/qrcodegen.md
Automatically detects the optimal encoding mode (numeric, alphanumeric, or byte) and creates an array of QrSegment objects. This is the primary API for encoding text into QR code segments.
```APIDOC
## QrSegment.makeSegments
### Description
Automatically detects optimal encoding mode and creates segment array. Handles empty strings, tests for all numeric, all alphanumeric, and defaults to byte segment (UTF-8) for other cases.
### Method
`static makeSegments(text: string): Array`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript
QrSegment.makeSegments('123') // → [numeric segment]
QrSegment.makeSegments('ABC123') // → [alphanumeric segment]
QrSegment.makeSegments('hello') // → [byte segment]
QrSegment.makeSegments('123abc') // → [byte segment] (mixed)
```
### Response
#### Success Response
- **Array** - An array of QrSegment objects representing the encoded text. Can be empty if the input string is empty.
```
--------------------------------
### Apply Standard HTML/SVG Attributes
Source: https://github.com/zpao/qrcode.react/blob/trunk/_autodocs/configuration.md
Style QR codes using standard HTML/SVG attributes like `style`, `className`, `id`, `role`, and `aria-label` for both `QRCodeSVG` and `QRCodeCanvas` components.
```javascript
// SVG example
```
```javascript
// Canvas example
```