How To Create/ Generate QRcode In SPFx Web Part

A QR Code is a 2-dimensional bar code, which is generally used to encode a URL so that the user can scan the code using his/her smartphone to visit the concerned site. The camera/s of the latest smartphones can scan the QR code without having to install a separate app. Paytm is an example of how people started using QRCode widely nowadays.

Installation

Inside your SPFx project folder, run the below command from the terminal or node command prompt

npm install --save qrcode

or, install it globally to use the QR Code from the command line to save QR code images or generate ones you can view in your terminal.

npm install -g qrcode

Usage

In your SPFx web part code, in the component file(.tsx/.ts), add the QR Code reference as below.

  1. var QRCode = require('qrcode');  

In the render() method, add the image tag to render the QR Code image.

  1. <img id="myQRcode" height="100%" width="100%" />  

Instead of using the canvas element, the publisher here is using an image element, because if one is required to save the image by right-clicking on the image in Internet Explorer, the option for ‘save as picture’ will not be available in case of the canvas element.

In the below example, I am generating a QR image which holds the current page URL. When the image needs to be appended on the page, trigger the below method using the button click.

  1. // Inside the render  
  2. <input type="button" onClick={() => this.createQRCode()} value="Create QR code" />  
  3.   
  4. // Method to create QR code  
  5. public createQRCode() {  
  6.         var opts = {  
  7.             errorCorrectionLevel: 'H',  
  8.             type: 'image/jpeg',  
  9.             rendererOpts: {  
  10.                 quality: 0.5  
  11.             }  
  12.         };  
  13. //adding current page url in the QR code  
  14.         QRCode.toDataURL(window.location.href.toString(), opts, function (err: any, imageGenerated: any) {  
  15.             if (err) throw err  
  16.   
  17.         //get the image element  
  18.             var img: any = document.getElementById('myQRcode');  
  19.             img.src = imageGenerated;// adding the image generated as source  
  20.             document.getElementById('myModal').style.display = "block";  
  21.         });  
  22.     }  

Output

How To Create/ Generate QRcode In SPFx Web Part 

Once the QR Code is generated, you can right click on the image and save it on the computer or you can scan it using your mobile phone.

How do I scan QR Codes with the phone camera?

  • Open the Camera app either from the lock screen or tapping on the icon from your home screen.
  • Hold your device steady for 2-3 seconds towards the QR Code you want to scan.
  • Click on the notification to open the content of the QR Code.