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.
- var QRCode = require('qrcode');
In the render() method, add the image tag to render the QR Code image.
- <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.
-
- <input type="button" onClick={() => this.createQRCode()} value="Create QR code" />
-
-
- public createQRCode() {
- var opts = {
- errorCorrectionLevel: 'H',
- type: 'image/jpeg',
- rendererOpts: {
- quality: 0.5
- }
- };
-
- QRCode.toDataURL(window.location.href.toString(), opts, function (err: any, imageGenerated: any) {
- if (err) throw err
-
-
- var img: any = document.getElementById('myQRcode');
- img.src = imageGenerated;
- document.getElementById('myModal').style.display = "block";
- });
- }
Output
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.