How to use React Native Camera to read QR codes

2020-02-07

React Native Camera is the go-to component when creating React Native apps that require the functionality of using the device’s camera. Maintained by the React Native community, this module has support for:

  • Videos
  • Photographs
  • Face Detection
  • Text Recognition
  • Barcode Scanning

It also helps your React Native app to communicate with the native operating system using the device's hardware by implementing some helper methods.

In this tutorial, let us build a simple QR code scanner app in React Native by implementing one of the functionalities this module supports, called Barcode scanning.

For more information on RNCamera, please refer to its official documentation here. The complete code for this tutorial is available at this GitHub repo.

Installing Dependencies

To begin, let us generate a React Native project by using the command below from a terminal window:

1npx react-native init qrCodeScannerApp
2
3# navigate inside the directory once its generated
4cd qrCodeScannerApp

Next, you have to install some dependencies to use the RNCamera module. If you are on the latest React Native version, that is, a version above 60.x.x, run the following command from a terminal window.

1yarn add react-native-camera

For iOS devices, you have to install the pods as shown below:

1# after dependency installation
2cd ios/
3
4pod install
5
6cd ..

For Android users, there is no extra installation requirement at this point.

Setting Camera Permissions

To access the device's hardware camera, a set of permissions have to be added. For iOS, please open the file ios/qrCodeScannerApp/Info.plist and add the following permissions:

1<!-- Required with iOS 10 and higher -->
2<key>NSCameraUsageDescription</key>
3<string>Your message to user when the camera is accessed for the first time</string>
4
5<!-- Required with iOS 11 and higher: include this only if you are planning to use the camera roll -->
6<key>NSPhotoLibraryAddUsageDescription</key>
7<string>Your message to user when the photo library is accessed for the first time</string>
8
9<!-- Include this only if you are planning to use the camera roll -->
10<key>NSPhotoLibraryUsageDescription</key>
11<string>Your message to user when the photo library is accessed for the first time</string>
12
13<!-- Include this only if you are planning to use the microphone for video recording -->
14<key>NSMicrophoneUsageDescription</key>
15<string>Your message to user when the microphone is accessed for the first time</string>

Next, to add permissions so that the app works correctly on an Android device, open the file android/app/src/main/AndroidManifest.xml and add the following:

1<!-- Required -->
2<uses-permission android:name="android.permission.CAMERA" />
3
4<!-- Include this only if you are planning to use the camera roll -->
5<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
6<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Then, open another file android/app/build.gradle and add the following:

1android {
2 ...
3 defaultConfig {
4 ...
5 // insert this line
6 missingDimensionStrategy 'react-native-camera', 'general'
7 }
8}

That's it for the installation process for the OS platforms. From the next section, let us continue to build the app.

Setting up the Camera in a React Native App

In this section, let us first try and test the RNCamera module. Open the App.js file and start by adding the following import statements. Nothing fancy here. You just have to import the core React Native components such as View and Alert as well as RNCamera from react-native-camera.

1import React, { Component } from 'react'
2import { StyleSheet, View, Alert } from 'react-native'
3import { RNCamera } from 'react-native-camera'

Then, create a class component App that is going to render the JSX that uses a hardware camera on the device's screen. This going to be done by wrapping the RNCamera component inside a View.

1class App extends Component {
2 render() {
3 return (
4 <View style={styles.container}>
5 <RNCamera
6 style={{ flex: 1, alignItems: 'center' }}
7 ref={ref => {
8 this.camera = ref
9 }}
10 />
11 </View>
12 )
13 }
14}
15
16const styles = StyleSheet.create({
17 container: {
18 flex: 1,
19 flexDirection: 'column',
20 backgroundColor: 'black'
21 }
22})
23
24export default App

After adding the above snippet, make sure you build the app for the OS you are using to test it. I am going to use a real Android device for testing.

1# for iOS
2react-native run-ios
3
4# for Android
5react-native run-android

When testing on an Android device, please make sure that the device is connected via USB, and make sure that USB debugging is enabled as well before you run the previous build command from a terminal window.

After the app has finished building and this process triggers the metro bundler, you are going to get a prompt asking for permission when the app runs for the first time.

js1

This means that the camera is working as expected and now you can leverage this to scan QR codes.

Reading a QR Code Information

To read the QR code information, you will have to make use of the prop onGoogleVisionBarcodesDetected. This prop, with the help of a helper method, can be used to evaluate the value of the scanned QR code.

In the App.js file, start by modifying the RNCamera component as below.

1<RNCamera
2 ref={ref => {
3 this.camera = ref
4 }}
5 style={styles.scanner}
6 onGoogleVisionBarcodesDetected={this.barcodeRecognized}
7/>

Add the corresponding styles for the Camera component in the previously defined StyleSheet object.

1const styles = StyleSheet.create({
2 container: {
3 flex: 1,
4 flexDirection: 'column',
5 backgroundColor: 'black'
6 },
7 // add the following
8 scanner: {
9 flex: 1,
10 justifyContent: 'flex-end',
11 alignItems: 'center'
12 }
13})

Then, before the render method, add the helper method barcodeRecognized as well the state variable barcodes whose initial value is going to be an array.

1state = {
2 barcodes: []
3}
4
5barcodeRecognized = ({ barcodes }) => {
6 barcodes.forEach(barcode => console.log(barcode.data))
7 this.setState({ barcodes })
8}

The above helper method is going to update the state variable barcodes that can be used to render the value of the QR code scanned using the RNCamera. Let us add two helper methods following the barcodeRecognized method. These helper methods are going to be responsible for displaying the information of the QR code.

1renderBarcodes = () => (
2 <View>{this.state.barcodes.map(this.renderBarcode)}</View>
3)
4
5renderBarcode = ({ data }) =>
6 Alert.alert(
7 'Scanned Data',
8 data,
9 [
10 {
11 text: 'Okay',
12 onPress: () => console.log('Okay Pressed'),
13 style: 'cancel'
14 }
15 ],
16 { cancelable: false }
17 )

Lastly, to render the Alert box, make sure you add the code below to modify the RNCamera component as below.

1<RNCamera
2 ref={ref => {
3 this.camera = ref
4 }}
5 style={styles.scanner}
6 onGoogleVisionBarcodesDetected={this.barcodeRecognized}
7>
8 {this.renderBarcodes}
9</RNCamera>

That's it! Now, let us go back to the app and test it out.

js3

Conclusion

The react-native-camera module can a perfect fit to leverage the device's hardware if you are building cross-platform apps with React Native.

In this tutorial, we only explored the barcode scanning capability, but the same principle applies if you have other goals in mind that also use the device’s camera.

Thanks to great community-built components like RNCamera, React Native apps continue to grow as great alternatives to native mobile apps.

Originally published at Jscrambler

I'm Aman working as an independent fullstack developer with technologies such as Node.js, ReactJS, and React Native. I try to document and write tutorials to help JavaScript, Web and Mobile developers.