featurepreneur
Published in

featurepreneur

Camera feature using React native

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:

npx react-native init qrCodeScannerApp 

# navigate inside the directory once it is generated
cd qrCodeScannerApp

Next, you have to install some dependencies to use the RNCamera module. If you are on the latest React Native version,

yarn add react-native-camera

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

# after dependency installation
cd ios/

pod install

cd ..

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:

<!-- Required with iOS 10 and higher -->
<key>NSCameraUsageDescription</key>
<string>Your message to user when the camera is accessed for the first time</string>

<!-- Required with iOS 11 and higher: include this only if you are planning to use the camera roll -->
<key>NSPhotoLibraryAddUsageDescription</key>
<string>Your message to user when the photo library is accessed for the first time</string>

<!-- Include this only if you are planning to use the camera roll -->
<key>NSPhotoLibraryUsageDescription</key>
<string>Your message to user when the photo library is accessed for the first time</string>

<!-- Include this only if you are planning to use the microphone for video recording -->
<key>NSMicrophoneUsageDescription</key>
<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:

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

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

android {  
...
defaultConfig {
...
// insert this line missingDimensionStrategy 'react-native-camera', 'general'

}
}

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.

import React, { Component } 
from 'react' import { StyleSheet, View, Alert }
from 'react-native' import { RNCamera }
from 'react-native-camera'
class App extends Component {
render() {
return (
<View style={styles.container}>
<RNCamera
style={{ flex: 1, alignItems: 'center' }}
ref={ref => {
this.camera = ref
}}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'black'
}
})
export 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.

# for iOS react-native run-ios  
# for Android react-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.

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.

<RNCamera
ref={ref => {
this.camera = ref
}}
style={styles.scanner}
onGoogleVisionBarcodesDetected={this.barcodeRecognized}
/>

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

const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'black'
},
// add the following
scanner: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center'
}
})

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.

state = {
barcodes: []
}
barcodeRecognized = ({ barcodes }) => {
barcodes.forEach(barcode => console.log(barcode.data))
this.setState({ barcodes })
}

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.

renderBarcodes = () => (
<View>{this.state.barcodes.map(this.renderBarcode)}</View>
)
renderBarcode = ({ data }) =>
Alert.alert(
'Scanned Data',
data,
[
{
text: 'Okay',
onPress: () => console.log('Okay Pressed'),
style: 'cancel'
}
],
{ cancelable: false }
)

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

<RNCamera
ref={ref => {
this.camera = ref
}}
style={styles.scanner}
onGoogleVisionBarcodesDetected={this.barcodeRecognized}>
{this.renderBarcodes}
</RNCamera>

here you go.

--

--

--

Microprediction/Analytics for Everyone! We help volunteers to do analytics/prediction on any data!

Recommended from Medium

Google Firebase Quick Look

Trying my hands at Deno 1.0

Make Realtime APIs with Node.js and React Using Socket.io

Some of the cool tricks in JavaScript

RxJS Basics — Transformation operators. Your BFF when dealing with multiple observable streams.

August 21th — 27th

100 Days of Generative Art Week 9:

Building a blog and admin dashboard with Netlify CMS and Gridsome

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Roughit srinivasan

Roughit srinivasan

Developer

More from Medium

Text strings must be rendered within a <Text> component. ReactNative

Use of Higher Order Component (Hoc) in React

A beginners guide to setting up redux-saga with Typescript using reduxsauce

React Native Deep Linking Tutorial — Real Life Case

Screenshot 1: apple-app-site-association