-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQRCode.tsx
More file actions
101 lines (89 loc) · 2.21 KB
/
QRCode.tsx
File metadata and controls
101 lines (89 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
* QR Code Component
*
* Generates an SVG QR code for the given URL.
* Uses the qrcode library for generation with error correction level M.
*/
import { useState, useEffect } from 'react';
import QRCodeLib from 'qrcode';
interface QRCodeProps {
/** URL to encode in the QR code */
value: string;
/** Size in pixels (width and height) */
size?: number;
/** Error correction level */
errorCorrection?: 'L' | 'M' | 'Q' | 'H';
/** Additional CSS class */
className?: string;
}
interface QRState {
svgString: string;
error: string | null;
}
export function QRCode({
value,
size = 200,
errorCorrection = 'M',
className = '',
}: QRCodeProps) {
const [state, setState] = useState<QRState>({ svgString: '', error: null });
useEffect(() => {
let cancelled = false;
async function generateQR() {
try {
const svg = await QRCodeLib.toString(value, {
type: 'svg',
errorCorrectionLevel: errorCorrection,
margin: 2,
width: size,
color: {
dark: '#000000',
light: '#FFFFFF',
},
});
if (!cancelled) {
setState({ svgString: svg, error: null });
}
} catch (err) {
if (!cancelled) {
setState({ svgString: '', error: err instanceof Error ? err.message : 'Failed to generate QR code' });
}
}
}
generateQR();
return () => {
cancelled = true;
};
}, [value, size, errorCorrection]);
if (state.error) {
return (
<div
className={`qr-code qr-code-error ${className}`}
style={{ width: size, height: size }}
role="img"
aria-label="QR code failed to generate"
>
<span>⚠</span>
</div>
);
}
if (!state.svgString) {
return (
<div
className={`qr-code qr-code-loading ${className}`}
style={{ width: size, height: size }}
role="img"
aria-label="Generating QR code"
/>
);
}
return (
<div
className={`qr-code ${className}`}
style={{ width: size, height: size }}
role="img"
aria-label={`QR code linking to ${value}`}
dangerouslySetInnerHTML={{ __html: state.svgString }}
/>
);
}