Search code examples
reactjsqr-codereact-pdf

want to get html component as image but always document.querySelector return null


I'm new to react. I'm using QRcode.react to generate a QR code & I'm hoping to add it to @react-pdf/renderer so I can attach QR code inside pdf. So for that, I'm trying to get HTML as a DataURL Of image.

below is my code for generating URL of the image

import React, { Fragment } from "react";

import QRCode from "qrcode.react";

class QRCodeRender extends React.Component {
  componentDidMount() {
    // console.log("im loded");
    const qrCodeCanvas = document.querySelector("target");
    const qrCodeDataUri = qrCodeCanvas.toDataURL("image/jpg", 0.3);
  }

  render() {
    const { cusName, invoice } = this.props;
    console.log("cusName props " + this.props.cusName);
    let data = `Customer : ${cusName} , Invoice : ${invoice}`;
    return (
      <Fragment>
        <div id="target">
          <QRCode level="Q" style={{ width: 60 }} value={data} />
        </div>
      </Fragment>
    );
  }
}

export default QRCodeRender;

problem is I always get in document.querySelector Null so I'm not able to create a URL of the HTML. am I doing it wrong?


Solution

  • You want to select the element with ID target. But what you chose is tag target.

    You need to fix this

        const qrCodeCanvas = document.querySelector("target");
    

    =>

        const qrCodeCanvas = document.querySelector("#target");