Create a Barcode Scanner Using React

Tiempo de lectura: 2 minutos

Today we are going to learn how to implement a barcode scanner using React.

The first thing we need to do is install the quagga2 library. You can also use quagga.

npm install @ericblade/quagga2 --save

Once installed, we are going to create a component called scanner.tsx

import Quagga from '@ericblade/quagga2';
import React, { useEffect, useCallback } from 'react';

interface ScannerProps {
    onDetected: (result: any) => void;
}

const Scanner: React.FC<ScannerProps> = ({ onDetected }) => {
    const _onDetected = useCallback((result: any) => {
        onDetected(result);
    }, [onDetected]);

    useEffect(() => {
        Quagga.init(
            {
                inputStream: {
                    type: 'LiveStream',
                    constraints: {
                        width: 640,
                        height: 480,
                        facingMode: 'environment', // or user
                    },
                },
                locator: {
                    patchSize: 'medium',
                    halfSample: true,
                },
                numOfWorkers: 4,
                decoder: {
                    readers: ["ean_reader"],
                },
                locate: true,
            },
            function (err) {
                if (err) {
                    return console.log(err);
                }
                Quagga.start();
            }
        );
        Quagga.onDetected(_onDetected);

        return () => {
            Quagga.offDetected(_onDetected);
            Quagga.stop(); // Stops scanning when the component unmounts
        };
    }, [_onDetected]);

    return <div id="interactive" className="viewport" style={{
        width: '640px', 
        height: '480px',
        margin: '0 auto'
    }}/>;
};

export default Scanner;

The scanner will recognize codes indicated in the decoder: { readers: [“ean_reader”, …]. To add more, you can check the quagga documentation:

Available codes:

    code_128_reader (default)
    ean_reader
    ean_8_reader
    code_39_reader
    code_39_vin_reader
    codabar_reader
    upc_reader
    upc_e_reader
    i2of5_reader
    2of5_reader
    code_93_reader

And now let’s use it in any of our screens:

First, create a state:

  const [resultScanner, setResultScanner] = useState<any>();

Now, get the state update:

  useEffect(() => {

    if (resultScanner!= undefined) {
      alert("Result Scan: " + JSON.stringify(resultScanner));
    }

  }, [resultScanner])

And now use it with the created component:

<Scanner onDetected={setResultScanner} />

Leave a Comment