React Native Barcode Scanner and QR Code Scanner using Camera

How to make an barcode scanner application using react native

React Native Barcode scaner

React Native Barcode scaner

React Native Barcode scanner with Camera

Hello Guyz!! I hope you are doing well today i am gonna show you that how to make React Native Barcode scanner. or how to scan a barcode using 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.

React Native Barcode scanner

So Guyz if are working on an app where you need to share small code/data/URL between users in physical presence then the QR Code must be the cool thing to integrate into your App.React Native Barcode scaner

Therefore we can see UPI or payment trasactions applications are the good example of it. so if you have some same kind of utility which needs to create a bar code or qr code then you can check the following example to generate the QR Code in react native application.

React Native Barcode scanner

In this blog series, you will make the QR Code and Barcode Scanner Using React Native Camera Device. We will here make a home page(screen) that contains a button which can be used to open QR Code and Barcode Scanner, this will open your device Camera with Barcode and QR Scan functionality and after scanning of the barcode or QR code, we will bring the data back to the home screen and show it there. That contains in the bar code

If that QR or Barcode code contains a URL the we will show an additional button to open the URL in default browser of the device by using React Native linking Component. So here we begin.

To Make a React Native App

So let’s begin. I am starting here from scratch with creating a React Native project. It 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. I am here Assuming that you have installed the latest version of node, 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 auto-linking 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

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.

React Native Barcode scanner
React Native Barcode scanner

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
  }
});

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).

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.

About Post Author