react-camera-scanner
v1.3.0
Published
Integrate camera-scanner to your React application using a custom hook
Downloads
28
Maintainers
Readme
Easily scan QR and ean codes in your React application. Exports a handy useCameraScanner
hook that utilizes the popular @zxing/library
to stream video to an element and decode codes from it.
Usage
import { useState } from "react";
import { useCameraScanner } from "react-camera-scanner";
export const BarcodeScanner = () => {
const [result, setResult] = useState("");
const { ref } = useCameraScanner({
onDecodeResult(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 { useCameraScanner } from "react-camera-scanner";
const constraints: MediaStreamConstraints = {
video: true,
audio: false,
};
export const BarcodeScanner = () => {
const { devices } = useMediaDevices({ constraints });
const deviceId = devices?.[0]?.deviceId;
const { ref } = useCameraScanner({
paused: !deviceId,
deviceId,
});
return <video ref={ref} />;
};
Advanced Usage
Torch
⚠️ Torch support is not available for iOS devices. See this issue.
You can control the torch by accessing the torch
property of the useCameraScanner
return value:
import { useCameraScanner } from "react-camera-scanner";
export const BarcodeScanner = () => {
const {
ref,
torch: { on, off, isOn, isAvailable },
} = useCameraScanner();
return (
<>
<video ref={ref} />
{isAvailable ? (
<button onClick={() => (isOn ? off() : on())}>
{isOn ? "Turn off" : "Turn on"} torch
</button>
) : (
<strong>Unfortunately, torch is not available on this device.</strong>
)}
</>
);
};
Torch support is limited to devices that support the torch
constraint. You can check if torch is available by checking the isAvailable
property.
Options
Development
# Install dependencies
yarn
# Build the library
yarn build
# Install example dependencies
yarn --cwd example
# Start the example
yarn --cwd example start
Example should now be running on localhost:1234.