Search code examples
javascriptreactjsdownloadqr-code

Make generated QR code downloadable on react project


What I'm trying to do is to generate a QR code based on the Device Id to later download it. I figured out how to generate it, it shows OK on the page, everything is ok but is there any possible way to download it? (the QR image, it's a .png)

import QRCode from 'qrcode.react';
render() {
return (
<QRCode value={this.state.values.deviceId} />
)};

This is what I've done:

Image 1

This is what I want to do:

enter image description here


Solution

  • I figured out how to do it, here is the code:

    import QRCode from 'qrcode.react';
    constructor(props) {
        super(props);
    this.download = this.download.bind(this);
    }
    componentDidMount(){
     this.download()
    }
    render() {
    return (
     <div style={{display: "none"}} className="HpQrcode"> // hidden div
       <QRCode
         value={this.state.values._id}
         size={128}
         level={'H'}
       />
     </div>
      <a ref={(ref: any): any => this.downloadRef = ref}>
        Download QR Code
      </a>
    )};
    download() {
        const canvas: any = document.querySelector('.HpQrcode > canvas');
        this.downloadRef.href = canvas.toDataURL();
        this.downloadRef.download = this.state.values.deviceId + "-QR.png";
    }