Generate Download & Scan QR Code with React JS

image

Creating a React application that scans QR codes using the camera and displays the data involves a few steps, including setting up a new React project (if you haven't already), installing necessary libraries, and writing the React component code to handle the QR code scanning and display. For QR code scanning, we'll use the react-qr-reader library, which simplifies the process of accessing the camera and decoding QR codes.


Step 1: Set Up Your React Project

If you haven't set up a React project yet, start by creating one with Create React App:

npx create-react-app qr-code-scanner
cd qr-code-scanner


Step 2: Install Dependencies

Install react-qr-reader to handle QR code scanning:

npm install react-qr-reader


Step 3: Create the QR Code Scanner Component

Create a new file QRCodeScanner.js in the src directory and add the following code:

import React, { useState } from 'react';
import QrReader from 'react-qr-reader';


function QRCodeScanner() {
  const [data, setData] = useState('No QR Code detected');


  const handleScan = data => {
    if (data) {
      setData(data);
    }
  };


  const handleError = err => {
    console.error(err);
  };


  return (
    <div>
      <QrReader
        delay={300}
        onError={handleError}
        onScan={handleScan}
        style={{ width: '100%' }}
      />
      <p>Scanned Data: {data}</p>
    </div>
  );
}


export default QRCodeScanner;


Step 4: Use the QR Code Scanner Component in Your App

Open the App.js file and import the QRCodeScanner component to use it:

import React from 'react';
import './App.css';
import QRCodeScanner from './QRCodeScanner';


function App() {
  return (
    <div className="App">
      <header className="App-header">
        <QRCodeScanner />
      </header>
    </div>
  );
}


export default App;


Step 5: Run Your Application

Start your React application:

npm start


This will run the app in development mode. Open localhost:3000 to view it in the browser. Point your app's camera at a QR code, and you should see the scanned data displayed on the screen.


Note: react-qr-reader uses the WebRTC API to access the camera, which is only available over HTTPS or localhost. If you deploy your app, make sure it's served over HTTPS.