Barcode and QR Code Scanner using Camera in React Native

React Native Barcode and QR Code Scanner

This is an Example of Barcode and QR Code Scanner using Camera in React Native. To make a Barcode and QR Code Scanner in React Native we are going to use a very good library provided by Wix named react-native-camera-kit. This library is very easy to integrate and the performance to scan the barcode or QR Code is very good.

Barcode v/s QR Code

A Barcode was the first to come in the market to store small numbers and representation of the information is 1 dimension.

QR code is the updated version of Barcode and stores more information than the Barcode and the representation of the information is 2 dimensions.

If you are making an app that needs to share small code/data/URL between users in physical presence then the QR Code is the cool thing to integrate into your App.

UPI or the payment transaction applications are the common example of it in which one user shows the QR Code and the other user scans the QR Code to initiate the payment. If you have the same utility which needs to create the QR Code then you can follow the example to Generate the QR Code in React Native Application.

In this example, you will make the Barcode and QR Code Scanner Using React Native Camera. We will make a home screen with a button to open Barcode and QR code scanner, this will open a Camera with Barcode and QR Scan functionality and after scanning of the barcode or QR code, we will take the data back to the home screen and show it there.

If the scanned data will be a URL then we will show an additional button to open the URL in default browser using React Native Linking Component. So let’s get started.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependency

To make the Barcode and QR Code scanner we are going to use CameraKitCameraScreen component from react-native-camera-kit library. To install this library open the terminal and jump into your project

cd ProjectName

Run the following command

npm install react-native-camera-kit --save

This command will copy all the dependencies into your node_module directory. –save is optional, it is just to update the react-native-camera-kit dependency in your package.json file.

CocoaPods Installation

After the updation of React Native 0.60, they have introduced autolinking so we do not require to link the library but need to install pods. So to install pods use

cd ios && pod install && cd ..

Permission to use the Camera for Android

We are using a Native API Camera to scan the Barcode and QR code so we need to add permission to the AndroidManifest.xml file to access it.

Please add the following permissions in your AndroidMnifest.xml. Go to QRScannerExample -> android -> app -> main -> AndroidMnifest.xml.

<uses-permission android:name="android.permission.CAMERA"/>
PermissionPurpose
CAMERATo access the camera


For more about the permission, you can see this post.

Permission to use the Camera for iOS

Please follow the below steps to add the permission in the iOS project to use the camera.

Open the project  QRScannerExample -> ios -> ScannerExample.xcworkspace in Xcode.

1. After opening the project in Xcode click on the project from the left sidebar and you will see multiple options in the workspace.

2. Select info tab which is info.plist

3. Click on the plus button to add a permission key “Privacy-Camera Usage Description” and a value that will be visible when permission dialog pops up.

Code to Make a Barcode and QR Code Scanner using Camera in React Native

Open App.js in any code editor and replace the code with the following code

App.js

//This is an example code to Scan QR code//
import React, { Component } from 'react';
//import react in our code.
import { Text, View, Linking, TouchableHighlight, PermissionsAndroid, Platform, StyleSheet} from 'react-native';
// import all basic components
import { CameraKitCameraScreen, } from 'react-native-camera-kit';
//import CameraKitCameraScreen we are going to use.
export default class App extends Component {
  constructor() {
    super();
    this.state = {
      //variable to hold the qr value
      qrvalue: '',
      opneScanner: false,
    };
  }
  onOpenlink() {
    //Function to open URL, If scanned 
    Linking.openURL(this.state.qrvalue);
    //Linking used to open the URL in any browser that you have installed
  }
  onBarcodeScan(qrvalue) {
    //called after te successful scanning of QRCode/Barcode
    this.setState({ qrvalue: qrvalue });
    this.setState({ opneScanner: false });
  }
  onOpneScanner() {
    var that =this;
    //To Start Scanning
    if(Platform.OS === 'android'){
      async function requestCameraPermission() {
        try {
          const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.CAMERA,{
              'title': 'CameraExample App Camera Permission',
              'message': 'CameraExample App needs access to your camera '
            }
          )
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            //If CAMERA Permission is granted
            that.setState({ qrvalue: '' });
            that.setState({ opneScanner: true });
          } else {
            alert("CAMERA permission denied");
          }
        } catch (err) {
          alert("Camera permission err",err);
          console.warn(err);
        }
      }
      //Calling the camera permission function
      requestCameraPermission();
    }else{
      that.setState({ qrvalue: '' });
      that.setState({ opneScanner: true });
    }    
  }
  render() {
    let displayModal;
    //If qrvalue is set then return this view
    if (!this.state.opneScanner) {
      return (
        <View style={styles.container}>
            <Text style={styles.heading}>React Native QR Code Example</Text>
            <Text style={styles.simpleText}>{this.state.qrvalue ? 'Scanned QR Code: '+this.state.qrvalue : ''}</Text>
            {this.state.qrvalue.includes("http") ? 
              <TouchableHighlight
                onPress={() => this.onOpenlink()}
                style={styles.button}>
                  <Text style={{ color: '#FFFFFF', fontSize: 12 }}>Open Link</Text>
              </TouchableHighlight>
              : null
            }
            <TouchableHighlight
              onPress={() => this.onOpneScanner()}
              style={styles.button}>
                <Text style={{ color: '#FFFFFF', fontSize: 12 }}>
                Open QR Scanner
                </Text>
            </TouchableHighlight>
        </View>
      );
    }
    return (
      <View style={{ flex: 1 }}>
        <CameraKitCameraScreen
          showFrame={false}
          //Show/hide scan frame
          scanBarcode={true}
          //Can restrict for the QR Code only
          laserColor={'blue'}
          //Color can be of your choice
          frameColor={'yellow'}
          //If frame is visible then frame color
          colorForScannerFrame={'black'}
          //Scanner Frame color
          onReadCode={event =>
            this.onBarcodeScan(event.nativeEvent.codeStringValue)
          }
        />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor:'white'
  },
  button: {
    alignItems: 'center',
    backgroundColor: '#2c3539',
    padding: 10,
    width:300,
    marginTop:16
  },
  heading: { 
    color: 'black', 
    fontSize: 24, 
    alignSelf: 'center', 
    padding: 10, 
    marginTop: 30 
  },
  simpleText: { 
    color: 'black', 
    fontSize: 20, 
    alignSelf: 'center', 
    padding: 10, 
    marginTop: 16
  }
});

We have used this website to generate the QR Code.

To Run the React Native App

Open the terminal again and jump into your project using.
cd ProjectName
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

Output Screenshots

Android

      
      

IOS

   

This is how you can make a Barcode and QR Code Scanner using Camera in React Native. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂


Related Posts

24 thoughts on “Barcode and QR Code Scanner using Camera in React Native”

  1. Great tutorial, can confirm it works. Just have one problem when flipping the camera side ways it gets distorted. Is there a fix for this? Cheers

    Reply
  2. Hi, I am trying to follow this example but it shows me an error: Invariant Violation: requireNativeComponent: “CameraView” was not found in the UIManager.

    I do not know what does it mean. I’m using Expo on Android device.

    Thank you!

    Reply
  3. hey the camera opens but nothing happens it does not scans the Qr code i have tried everything got any solution ?

    Reply
  4. Is it possible to set time out and re initiate to scanner? Some times i am facing it’s unable to scan the code for a longer time. My intention is to set timeout for some time. And when it’s unable to read the code it will show some message something like “Unable to scan, try again”. And when user click on it it will again re initiate the camera to scan. Please let me know how to do this

    Reply
  5. Hello sir, You always has a very good tutorial explaination of every library.

    can you please help me with this scenario ->>>>

    My react native app needs to scan a QR Code/Bar Code and stores the data of that QR code if present in the Object which we are capturing otherwise it has to simply take photo of that object.
    How to do this in a single step ?

    Reply
  6. Hi, i ran into a problem. The app worked fine when showFrame value is set to false but when i set it to true the app didn’t detect any qr or barcode. Can you help me? Thank you very much!

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.