Easily scan QR and ean codes in your React application
Easily scan QR and ean codes in your React application. Exports a handy useZxing
hook that utilizes the popular @zxing/library
to stream video to an element and decode codes from it.
Usage
import { useState } from "react";
import { useZxing } from "react-zxing";
export const BarcodeScanner = () => {
const [result, setResult] = useState("");
const { ref } = useZxing({
onResult(result) {
setResult(result.getText());
},
});
return (
<>
<video ref={ref} />
<p>
<span>Last result:</span>
<span>{result}</span>
</p>
</>
);
};
With specific device ID
You could either get the device ID from the MediaDevices
API yourself or make use of react-media-devices to list available devices:
import { useMediaDevices } from "react-media-devices";
import { useZxing } from "react-zxing";
const constraints: MediaStreamConstraints = {
video: true,
audio: false,
};
export const BarcodeScanner = () => {
const { devices } = useMediaDevices(constraints);
const { ref } = useZxing({
deviceId: devices[0].deviceId,
});
return <video ref={ref} />;
};
Options
Name | Type | Default | Description |
---|---|---|---|
onResult | function | Called when a result is found. The result is an instance of Result . | |
onError | function | Called when an error is found. The error is an instance of Error. | |
hints | Map<DecodeHintType, any> | A map of additional parameters to pass to the zxing decoder. | |
timeBetweenDecodingAttempts | number | 300 | The time in milliseconds to wait between decoding attempts. |
constraints | MediaStreamConstraints | { video: { facingMode: ‘environment’ }, audio: false } | The constraints to use when requesting the camera stream. |
deviceId | string | You may pass an explicit device ID to stream from. |