Implementing a QR Code Scanner in React

QR Code Scanners are extremely popular and here's how to implement it in React. It is simple enough to implement but if building from scratch, it might take your whole day.

Luckily, I'm here to help you out.

Problem: Although we have a lot of plug-in-play types of QR Code Scanner packages dedicated to React, many are not that stable, some have bugs specific to a certain browser, some don't have enough flexibility to use and some just lack certain features.

Solution: I found out that QR Code Scanner packages that have a direct implementation with JavaScript, rather than specialize with a certain JS Framework, are much better and stable.

Package Used

I'll be using the qr-scanner package which is pretty stable and is sponsored by nimiq (which is a browser-based blockchain and i guess they use this package in their application too).

Let's Code

a. Folder Structure

I'm using vite to setup development environment. But, you can use anything of your choice, even create-react-app.

-node_modules and others
-package.json
-src
  -assets
    -qr-frame.svg
  -components
    -QrReader.tsx
    -QrStyles.css
  -App.tsx
  -main.tsx
  -App.css   (this is an empty file)
  -index.css (this is an empty file)

b. Install Package

npm i qr-scanner

c. Clean Unwanted CSS

I've deleted all the css from App.css and index.css so that i'll have a clean slate to work on and also so that css styles don't conflict each other. This is all the css styles we'll need for our QR Scanner:

.qr-reader {
  width: 430px;
  height: 100vh;
  margin: 0 auto;
  position: relative;
}

.qr-reader video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.qr-reader .qr-box {
  width: 100% !important;
  left: 0 !important;
}

.qr-reader .qr-frame {
  position: absolute;
  fill: none;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
}

/* Media Queries for mobile screens */
@media (max-width: 426px) {
  .qr-reader {
    width: 100%;
  }
}

d. Import Dependencies

Let's make a QrReader component in /components/QrReader.tsx and import qr-scanner, QrFrame and QrStyles.css:

// Styles
import "./QrStyles.css";

// Qr Scanner
import QrScanner from "qr-scanner";
import QrFrame from "../assets/qr-frame.svg";

const QrReader = () => {

}

export default QrReader;

The essay continues, with the scanner logic and camera handling, on Medium.


First published on Medium in the readytowork publication, 7 January 2024.

9