Search code examples
reactjsqr-codehtml2canvas

Can't access toDataUrl() using the useRef hook?


I'm generating a QRCode in my functional component. I want to copy the QRcode to clipbaord or download the QRcode. Im passing a Ref into the QRCode component. But I can't use the ref.current.toDataUrl() inside my listener.

React package - react-qrcode-logo

I tried with 2 different approaches.

  1. downloadQR() -> Doesn't work. I guess this is not supposed to work cause Im using react hooks.

2.downloadQR2() -> It says that toDataURL() is undefined for the ref.

console.log(containerRef.current) printed this on the console.
enter image description here

    const downloadQR2 = () => {
        const canvas = containerRef.current;
        console.log(canvas.toDataURL());
    }

    const downloadQR = () => {
        const canvas = document.getElementById("canvas-id");
        const pngUrl = canvas
          .toDataURL("image/png")
          .replace("image/png", "image/octet-stream");
        let downloadLink = document.createElement("a");
        downloadLink.href = pngUrl;
        downloadLink.download = "QRcode.png";
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
      };

//Componenet
   <QRCode id="canvas-id" ref={containerRef} value={url} logoImage={stackedLogo}/>

Im pretty new in React. Im lost on how to approach the task? Could anyone please share some insight or point me in the right direction?


Solution

  • The problem is containerRef.current is QRCode component. It is not canvas. As you can see from the log, canvas is containerRef.current.canvas.current.