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

// Barcode and QR Code Scanner using Camera in React Native
// https://aboutreact.com/react-native-scan-qr-code/

// import React in our code
import React, {useState} from 'react';

// import all the components we are going to use
import {
  SafeAreaView,
  Text,
  View,
  Linking,
  TouchableHighlight,
  PermissionsAndroid,
  Platform,
  StyleSheet,
} from 'react-native';

// import CameraKitCameraScreen
import {CameraKitCameraScreen} from 'react-native-camera-kit';

const App = () => {
  const [qrvalue, setQrvalue] = useState('');
  const [opneScanner, setOpneScanner] = useState(false);

  const onOpenlink = () => {
    // If scanned then function to open URL in Browser
    Linking.openURL(qrvalue);
  };

  const onBarcodeScan = (qrvalue) => {
    // Called after te successful scanning of QRCode/Barcode
    setQrvalue(qrvalue);
    setOpneScanner(false);
  };

  const onOpneScanner = () => {
    // To Start Scanning
    if (Platform.OS === 'android') {
      async function requestCameraPermission() {
        try {
          const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.CAMERA,
            {
              title: 'Camera Permission',
              message: 'App needs permission for camera access',
            },
          );
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            // If CAMERA Permission is granted
            setQrvalue('');
            setOpneScanner(true);
          } else {
            alert('CAMERA permission denied');
          }
        } catch (err) {
          alert('Camera permission err', err);
          console.warn(err);
        }
      }
      // Calling the camera permission function
      requestCameraPermission();
    } else {
      setQrvalue('');
      setOpneScanner(true);
    }
  };

  return (
    <SafeAreaView style={{flex: 1}}>
      {opneScanner ? (
        <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) =>
              onBarcodeScan(event.nativeEvent.codeStringValue)
            }
          />
        </View>
      ) : (
        <View style={styles.container}>
          <Text style={styles.titleText}>
            Barcode and QR Code Scanner using Camera in React Native
          </Text>
          <Text style={styles.textStyle}>
            {qrvalue ? 'Scanned Result: ' + qrvalue : ''}
          </Text>
          {qrvalue.includes('https://') ||
          qrvalue.includes('http://') ||
          qrvalue.includes('geo:') ? (
            <TouchableHighlight onPress={onOpenlink}>
              <Text style={styles.textLinkStyle}>
                {
                  qrvalue.includes('geo:') ?
                  'Open in Map' : 'Open Link'
                }
              </Text>
            </TouchableHighlight>
          ) : null}
          <TouchableHighlight
            onPress={onOpneScanner}
            style={styles.buttonStyle}>
            <Text style={styles.buttonTextStyle}>
              Open QR Scanner
            </Text>
          </TouchableHighlight>
        </View>
      )}
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    padding: 10,
    alignItems: 'center',
  },
  titleText: {
    fontSize: 22,
    textAlign: 'center',
    fontWeight: 'bold',
  },
  textStyle: {
    color: 'black',
    fontSize: 16,
    textAlign: 'center',
    padding: 10,
    marginTop: 16,
  },
  buttonStyle: {
    fontSize: 16,
    color: 'white',
    backgroundColor: 'green',
    padding: 5,
    minWidth: 250,
  },
  buttonTextStyle: {
    padding: 5,
    color: 'white',
    textAlign: 'center',
  },
  textLinkStyle: {
    color: 'blue',
    paddingVertical: 20,
  },
});

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 (macOS only)

react-native run-ios

Download Source Code

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

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

    • You can control it with the outer container. By default, CameraKitCameraScreen has flex 1 and it takes the full space available in the parent container so you can manage it with the help of outer View.

      Reply
  1. 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

Leave a Comment

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