Giter Site home page Giter Site logo

react-zxing's Introduction



📷
react-zxing


npm i react-zxing

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({
    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 { useZxing } from "react-zxing";

const constraints: MediaStreamConstraints = {
  video: true,
  audio: false,
};

export const BarcodeScanner = () => {
  const { devices } = useMediaDevices({ constraints });
  const deviceId = devices?.[0]?.deviceId;
  const { ref } = useZxing({
    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 useZxing return value:

import { useZxing } from "react-zxing";

export const BarcodeScanner = () => {
  const {
    ref,
    torch: { on, off, isOn, isAvailable },
  } = useZxing();

  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

Name Type Default Description
onDecodeResult function Called when a decode result is found. The result is an instance of Result .
onDecodeError function Called when an decode error is found. The error is an instance of Exception
onError function Called when any other error occurs, e.g. when the camera stream cannot be accessed.
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.
paused boolean false Stops the camera stream when true.

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.

react-zxing's People

Contributors

adamalfredsson avatar hummusonrails avatar apaleslimghost avatar nischay2x avatar

Stargazers

 avatar Christiane Celeste avatar Tim Greaves avatar Dzmitry Zubakin avatar Steffen Stamprath avatar  avatar  avatar  avatar Jean León avatar Evgenii Perminov avatar Mr.chu avatar Shagun Sharma avatar Viktor Sokolov avatar Jochen Seeber avatar Ramadan Omar avatar Mehedi Hasan Siam avatar William Becher avatar Bam Faboyede avatar Marcus Paulo Oliveira avatar  avatar Avinash Kumar avatar Bruno Wego avatar Albert Shin avatar Felipe Cantieri Testoni avatar  avatar Priyank avatar Dalibor Homola avatar MUHAMMAD MANNIR AHMAD avatar martin. avatar glani kali avatar  avatar Chirag Bhansali avatar Eduardo Grigolo avatar Ze-Zheng Wu avatar Daniel avatar Saeed Kefayati avatar pedro avatar William X avatar Luiz Felipe Warmling Amadeu avatar Ramon Cardena avatar Jared Prather avatar Ethra avatar Chas Turansky avatar  avatar tufusa avatar  avatar Cyberlife avatar LaoHan avatar Anton Larionov avatar Kosuke Adachi avatar Aritro Saha avatar Alain Kaiser avatar m-nohara avatar DevOps Interaktu avatar Ahmet Rasit Degirmencioglu avatar FELIPE RODRIGUES DE MELO avatar  avatar  avatar Naughty Ghost avatar  avatar Haikel avatar kazem ghanati avatar Albert Riedinger avatar Kenroy George avatar happyhourDAO avatar  avatar Tamas avatar Dalibor Homola avatar  avatar  avatar GyuJae avatar Brandon Swenson avatar Mani Nilchiani avatar SatoKoga avatar eno1220 avatar Ricardo avatar Muhammad Azka avatar  avatar Erik Tiekstra avatar Marcos Henrique avatar Luis Pericchi  avatar Domagoj avatar Ice cream avatar Roxana Bita avatar Kenneth Bass avatar Yilin (Kevin) Ren avatar Azddine Elmoumny avatar  avatar Sung avatar  avatar BonyChops avatar Nanodebug avatar Orlando Garcia avatar Matthias Prieth avatar Ramazan ERTAN avatar Subhan Bakhtiyarov avatar  avatar Christian Teobaldo avatar

Watchers

 avatar  avatar  avatar

react-zxing's Issues

Warning: Trying to play video that is already playing

Hi,
Thanks for this helpful package for react.
After implementing it, When I start this camera, It shows a warning in console Trying to play video that is already playing.

I have tried and checked my codes, but seems like it has issues with the package.
Can you please check or guide me how can I fix this?

Thanks

Implement zxing-wasm

Hi, @adamalfredsson, hope you're well.

I'm the owner of zxing-wasm which is an ES module WebAssembly build wrapper of an actively maintained cpp port of ZXing zxing-cpp. zxing-wasm has smaller sizes, can read more barcode formats, has better performance and more decode hints to configure. It can also read mirrored or color-inverted barcodes.

As I know @zxing/library is in maintenance mode now and there won't be any active feature updates in the foreseeable future. I was wondering if we can join forces and integrate the zxing-wasm package into this repo?

I'm also expecting more feedbacks on the API or other things so I can make proper adjustments before releasing the first official version.

BTW, I have an another repo barcode-detector which serves as a polyfill of the Barcode Detection API of web browsers, that is built upon zxing-wasm. And barcode-detector is utilized in vue-qrcode-reader which is something like this repo but for Vue.js users. I have made some contributions there, and I think there're some common issues we can learn and solve together, especially those related to camera behaviors on different devices.

Originally posted by @Sec-ant in #19 (comment)

npm package outdated

Hey! I installed this package from npm, but it seems to be outdated. The version number is 2.0.0, but some of the new features that you have added are not available.

From the npm package:

interface UseTorchOptions {
    resetStream: () => void;
}
export declare const useTorch: ({ resetStream }: UseTorchOptions) => {
    init: (videoTrack: MediaStreamTrack) => void;
    status: "idle" | "on" | "off" | "unavailable";
    on: () => Promise<void>;
    off: () => Promise<void>;
};
export {};

Manually packing from your repo:

interface UseTorchOptions {
    resetStream: () => void;
}
export declare const useTorch: ({ resetStream }: UseTorchOptions) => {
    init: (videoTrack: MediaStreamTrack) => void;
    isOn: boolean;
    isAvailable: boolean | null;
    on: () => Promise<void>;
    off: () => Promise<void>;
};
export {};

If you could publish it again that would be great!

no *.ts files not found warning in xzing/library

hello awesome hook
but i have problems, this is my package.json

{
"name": "pwa-app-lectorqr2",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^17.0.45",
"@types/react": "^18.0.26",
"@types/react-dom": "^18.0.9",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"react-zxing": "^1.0.5",
"typescript": "^4.9.3",
"web-vitals": "^2.1.4",
"workbox-background-sync": "^6.5.4",
"workbox-broadcast-update": "^6.5.4",
"workbox-cacheable-response": "^6.5.4",
"workbox-core": "^6.5.4",
"workbox-expiration": "^6.5.4",
"workbox-google-analytics": "^6.5.4",
"workbox-navigation-preload": "^6.5.4",
"workbox-precaching": "^6.5.4",
"workbox-range-requests": "^6.5.4",
"workbox-routing": "^6.5.4",
"workbox-strategies": "^6.5.4",
"workbox-streams": "^6.5.4",
"zxing-typescript": "^0.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
many warnings appear, that it does not find the files in xzing *.ts

Still open the app.
thank you very much for your help

image

feature for the lib tip

  1. Visual Indicators:
  • Provide visual cues to guide users on where to position the barcode within the scanning area.
    it can be reference lines, corners, or other visual elements to help users align the barcode correctly.
  1. Customizable Positioning and Sizing:
  • By default, react-zxing scans the entire video frame for codes. However, you can add the possibility to set specific coordinates for scanning.

  • Allow developers to define a rectangular region within the video frame where the scanner should focus. This way, users won’t need to spend time locating the exact spot for scanning.

  • Additionally, consider allowing users to resize this scanning area on the screen. This flexibility ensures that even if a mobile phone camera isn’t focusing closely on the barcode, the user can adjust the position.

Detecting failed permission and

Hello, great library! Thanks.

If the user refuses to grant permission, should this through an error to the error handler?

At least on Safari, instead it logs an unhandled rejection:

Screenshot from 2023-06-02 16-55-56

Or could it be another state variable like isTorchAvailable, "isCameraAvailable"?


Also on another related note I wanted to overlay some controls on the video, and I found making use of:

  const [ready, setReady] = useState(false);
  useEffect(() => {
    // Only show overlay with controls (torch, close) once actual video stream is displayed.
    const loadedListener = (e) => setReady(true);
    if (ref.current) ref.current.addEventListener('loadeddata', loadedListener);
    return () => current?.removeEventListener('loadeddata', loadedListener);
  }, [paused]);

Since there's already the ref to the video in case this is helpful to anyone.

Thanks again, one of the few react qrcode libraries that work out of the box these days.

Error when attempting to run

Hello,

I simply cloned and for the Example I ran "yarn", then "yarn start" and I get the following error:

@parcel/core: Failed to resolve 'react/jsx-dev-runtime' from './src/index.tsx'

C:\Development\React\Scanner\react-zxing-main\example\src\index.tsx:1:1

1 | import React from "react";
| ^
2 | import ReactDOM from "react-dom/client";
3 | import App from "./App";

Any idea what might be the cause?

Thanks in advance.

Video flickers/updates when state outside of <video> updates

Hey,
so whenever my state outside of the <video> updates, also the <video> updates, so I see a quick flickering and it resets the height of the video, video goes black and reloads. Is this normal? Maybe it has something to do with the ref being passed to <video ref={ref} />, but I don't get it? Does the default example have the same problem for you, cause it also has a state?
Cheers

inverted qrcode

Hi there,

thank you for your effort. That helped us much.

Is it possible to adjust your work for reading the inverted contrast qrcodes?

ps. I guess the zxing/library has a built-in InvertedLuminanceSource class, whereas I could not find out where to set that class as the input for the BrowserMultiFormatReader.

Thanks in advance

Eanble Torch

I would be better if there's an option to enable torch. Is it possible to enable torch externally even with the camera is ued by zxing.

Torch is not working

I am encountering an issue with the torch.on() and torch.off() functions. When I call torch.on(), no noticeable changes occur, even console don't log any message.

I´m using the latest version 1.1.4

Uncaught (in promise) DOMException: Could not start video source (on Android and using react-media-devices)

Hi,
sorry for bothering, but I have another problem when using react-zxing and react-media-devices together.
I wanted to implement a "Camera switch" and I'm using a similar code as in the documentation.
"react-media-devices": "1.1.0"
"react-zxing": "1.0.4",

import { useMediaDevices } from "react-media-devices";
import { useZxing } from "react-zxing";

const constraints: MediaStreamConstraints = {
  video: true,
  audio: false,
};

export const BarcodeScanner = () => {
  const { devices, loading } = useMediaDevices(constraints);
  //... 
  //here I filter the devices 
  //...
  const { ref } = useZxing({
    deviceId: devices[videoDeviceIndexFromLocalStorage].deviceId,
  });

  return <video ref={ref} />;
};

So whenever I use useMediaDevices(to get the list of available devices) before react-zxing it leads to the following error ONLY on Android devices:
image

It seems that Android devices are typically limited to one open camera at a time like described here and that useMediaDevices blocks a stream, video or track that react-zxing needs:
https://stackoverflow.com/questions/53139293/domexception-could-not-start-video-source-with-zxing-and-bootstrap-4-modal

I've tried a few things to initialize useMediaDevices differently but I can't, cause it's a hook & I've tried a few suggestions regarding closing the media streams after getting the devices, but It didn't work for me: https://stackoverflow.com/questions/11642926/stop-close-webcam-stream-which-is-opened-by-navigator-mediadevices-getusermedia

Any ideas on how to solve that? Thx!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.