Search code examples
javascriptreactjstypescriptqr-code

canvas.toDataURL() is not a function


I'm trying to download a generated QRCode from the react-qr-code library but I'm stuck at the step of actually downloading the image.

import QRCode from "react-qr-code";

I generate the QRCode inside my React component like so:

return(
.
.
.
    <QRCode id="qrcode" level="H" value={box.id} size={100} />
    <Button onClick={downloadQRCode}>Download QR</Button>
);

my download function:

 const downloadQRCode = () => {
    const canvas = document.getElementById("qrcode") as HTMLCanvasElement;
    if (!canvas) throw new Error("Canvas not found");
    const pngUrl = canvas
      .toDataURL("image/png")
      .replace("image/png", "image/octet-stream");
    let downloadLink = document.createElement("a");
    downloadLink.href = pngUrl;
    downloadLink.download = `${box.id}.png`;
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
  };

if I console.log(canvas) before trying to toDataURL it's got the correct svg. However, when I run the downloadQRCode function all I get is:

Uncaught TypeError: canvas.toDataURL is not a function

Solution

  • I got it working by switching the library from react-qr-code, which doesn't seem to the best library for this to qrcode.react.

    This lets me use <QRCodeCanvas/> and <QRCodeSVG/> elements.

    Using the QRCodeCanvas like was suggested in the comments solved this issue.

    <QRCodeCanvas id="qrcode" level="H" value={box.id} size={100} />
    <Button onClick={downloadQRCode}>Download QR</Button>