Handle Barcode scan in React application

Viewed 29

I am implementing a barcode Scanning thing in React application. The goal is to scan the barcode and add that product to the cart.

I tried using react-qr-barcode-scanner npm package. Below is the code I have implemented.

import React from 'react';
import BarcodeScannerComponent from 'react-qr-barcode-scanner';

function App() {
  const [data, setData] = React.useState('Not Found');
  const [stopStream, setStopStream] = React.useState(false);

  return (
    <>
      <BarcodeScannerComponent
        width={500}
        height={500}
        stopStream={stopStream}
        onUpdate={(err, result) => {
          if (result) {
            console.log('onUpdate');
            setData(result.text);
            setStopStream(true);
          } else {
            setData('Not Found');
          }
        }}
      />
      <p>{data}</p>
    </>
  );
}
export default App;

With this whenever I tried scanning the bar code I'm not getting the console log and the state is also not getting updated. But If I keep my cursor in any input text field then the scanner reads and enters the value in a text field so the scanner is working as expected, But I don't want to add any text field. I want a customer to stay on the cart page and anytime he scans something that product should be added to a cart.

https://stackblitz.com/edit/react-uwam1v

0 Answers
Related