I often need to generate a QR code quickly during the day and don’t want to jump through hoops.
I don’t want to hit a paywall after clicking on the top search result. I don’t care about tracking, analytics, or whatever else you’re selling—I just want my damn code.
To put an end to my suffering, I put together a simple one...
Code
npm install qrcode.react
"use client";
import { QRCodeSVG } from "qrcode.react";
import { useState } from "react";
import Button from "../ui/button";
import Input from "../ui/input";
export default function QRCodeGenerator() {
const [text, setText] = useState("");
const downloadQRCode = () => {
// create a temporary canvas element
const canvas = document.createElement("canvas");
const svg = document.getElementById("qrcode");
const svgData = new XMLSerializer().serializeToString(svg);
const img = new Image();
// convert SVG to data URL
const svgBlob = new Blob([svgData], {
type: "image/svg+xml;charset=utf-8",
});
const svgUrl = URL.createObjectURL(svgBlob);
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// create download link
const a = document.createElement("a");
a.download = "qrcode.png";
a.href = canvas.toDataURL("image/png");
a.click();
// cleanup
URL.revokeObjectURL(svgUrl);
};
img.src = svgUrl;
};
return (
<div className="flex flex-col items-center gap-8 max-w-md mx-auto">
{text && (
<QRCodeSVG
id="qrcode"
value={text}
size={512}
className="w-full h-auto"
bgColor="#ffffff"
fgColor="#000000"
/>
)}
<Input
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Enter something to encode..."
/>
<Button onClick={downloadQRCode}>Download</Button>
</div>
);
}