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 command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
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 CameraScreen
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
Please use the following command to install CocoaPods
npx pod-install
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"/>
Permission | Purpose |
---|---|
CAMERA | To access the camera |
For more about the permission, you can see this post. Also, you need to do these changes in your project.
Permission to use the Camera for iOS
Please follow the below steps to add 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 the 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 the 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 CameraScreen
import {CameraScreen} 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}}>
<CameraScreen
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
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
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 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. 🙂
Great tutorial, can confirm it works.
Thanks very much for the solution, congratulations
This really works! But how do I size the frame in the CameraKitCameraScreen component?
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.
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
Yeah sure, you can use Timeout and can change the state of this.state.opneScanner If you need how to do that then you can see this example https://aboutreact.com/animated-splash-screen/. In the example suggested look into the constructor where I have set a Timeout of 3 sec(3000 MiliSec)
Awesome example
ios in not working
error :reactmnative component : ” CKCamera” was not found in the UIManager
Found any solution?
I am using Expo wrapper over React Native project, it don’t have AndroidManifest.xml file in directory.
can I proceed without asking for permission.
You need to use any other library for the expo. This example is for native development only without expo.
Not working,
A problem occurred evaluating project ‘:react-native-camera-kit’.
> Plugin with id ‘kotlin-android’ not found.
&
A problem occurred configuring project ‘:react-native-camera-kit’.
> compileSdkVersion is not specified. Please add it to build.gradle
Can you please try this
Is there a method to capture an image of the barcode/qr code when onReadCode fires?
You can integrate screenshot capturing. Please have a look at React Native Example to Take Screenshot Programmatically
> Configure project :react-native-camera-kit
WARNING: The following project options are deprecated and have been removed:
android.useDeprecatedNdk
NdkCompile is no longer supported
Please have a look at this
How QR code save for gallery ???
Is there any difference when using iPad/tablet?