useBarcodeDetection
React hook for detecting barcodes.
This hook wraps the BarcodeDetection API which has (very) limited support. If you know or can control what browser your users use this might be for you, but if not it's not recommended for use in production. Be sure to check the browser compatability table.
Installation
npm i use-barcode-detection
Usage
import useBarcodeDetection from "use-barcode-detection";
const ScannerComponent = () => {
const [isScanning, setIsScanning] = useState(false);
const onDetected = (barcodes: string[]) => {
// Handle barcode detection...
console.log(barcodes);
// Deactivate scanning, maybe close a modal...
setIsScanning(false);
};
const { ref } = useBarcodeDetection({
interval: 150,
active: isScanning,
onDetected,
});
return (
<>
<video ref={ref} autoPlay playsInline muted />
<button onClick={() => setIsScanning(!isScanning)}>
{isScanning ? "Stop scanning" : "Start scanning"}
</button>
</>
);
};
TODO
- Better error handling
- Add API reference
- Tests
- ...