How to use barcode reader in a React application

Hanggi Anggono
2 min readSep 18, 2020

--

A barcode reader

Recently i’ve been working on a React App which has a barcode reading capability. The app has some kind of a transaction page and when you scan a barcode of a product, the product will show on the page. The project used react-barcode-reader library.

From the documentation, the usage of this library is as simple as follows:

<BarcodeReader
onError={this.handleError}
onScan={this.handleScan}
/>

You can use onScan props to detect scan event, and you will get the data of the scanned barcode. The old maintainer of my project used this and it worked as expected.

Things getting bad when we bought a new barcode reader device. The onScan props doesn’t works for this new barcode reader, but it works for the old one. So i tried to debug each device, and found out that they have different behaviour on how the scan works. The old one uses a copy-paste like mechanism, while the new one types the characters inside the barcode one by one (it’s fast but still noticeable).

The workaround is to listen to onReceive callback and store the characters into a state. If the received characters is an Enter key then call the custom onScan props and reset the state to empty string. I created a custom component based on react-barcode-reader to overcome my issue. I wonder if this is the best way i can handle it, anyway hope it helps anyone with the same issue.

--

--