Building a React Native Barcode and QR Scanner

Building a React Native Barcode and QR Scanner

Adding a barcode or QR code scanner can be an excellent way to streamline user interactions while you are developing mobile applications. React Native is straightforward for various tasks like scanning product codes, even tickets, or payment links.

In this blog, we are going to walk you through the entire process of creating a functional barcode and QR scanner with the help of React Native. So let’s get started!

Table of Contents:

Introduction to React Native Barcode and QR Scanning

React Native provides a versatile platform for developing mobile applications with JavaScript. One of the key features of React Native is the ability to integrate barcode and QR scanning functionality into your applications. Barcode and QR scanning have become essential in various industries, such as retail, inventory management, and ticketing systems.

Setting Up the React Native Development Environment

Before diving into barcode and QR scanning, we need to ensure that our development environment is properly configured. Here are the steps to set up a React Native project:

  • Install Node.js and npm: Node.js is required to run the React Native development server and manage dependencies. Check that you have the most recent stable version installed.
  • Install React Native CLI: The React Native CLI allows you to create, build, and run React Native applications from the command line. Run the following command to install it globally:

npm install -g react-native-cli

  • Create a New React Native Project: Use the following command to create a new React Native project with a specific name (e.g., BarcodeScannerApp):

react-native init BarcodeScannerApp

  • Start the Development Server: Navigate to the project directory and start the development server using the following command:

cd BarcodeScannerApp
react-native start

Get 100% Hike!

Master Most in Demand Skills Now!

Building the User Interface

After setting up the development environment, we can begin to build the user interface for our barcode and QR scanner application. The user interface should include a view where the camera will display the captured image and a button to initiate the scanning process.

To create the user interface, we can use the components provided by React Native, such as View, Text, and Button. We’ll create a screen component and style it using CSS-like properties. Here’s an example of a simple user interface for our barcode scanner:

import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
const ScannerScreen = () => {
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Barcode Scanner</Text>
      <View style={styles.cameraView}>
        {/* Camera preview will be displayed here */}
      </View>
      <Button title="Scan" onPress={handleScan} />
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  cameraView: {
    width: '80%',
    height: 200,
    borderWidth: 1,
    borderColor: 'black',
    marginBottom: 20,
  },
});
export default ScannerScreen;

Integrating Barcode and QR Scanner Libraries

To enable barcode and QR scanning functionality in your React Native application, you can leverage popular libraries such as react-native-camera or react-native-qrcode-scanner. These libraries provide pre-built components and APIs that simplify the scanning process.

Let’s take a closer look at the integration process using the react-native-camera library:

1. Install the Library

In your project directory, run the following command to install the react-native-camera library:
npm install react-native-camera

2. Link the Library

Link the library to your project using the following command:
react-native link react

3. Update the User Interface

Import the necessary components from react-native-camera and update the ScannerScreen component to render the camera preview. You can add a method to handle the scanning process and access the captured data.

Example Usage

import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import { RNCamera } from 'react-native-camera';

const ScannerScreen = () => {
const [scannedData, setScannedData] = useState(null);
const [isScanning, setIsScanning] = useState(false);

return (
<View style={styles.container}>
{isScanning && (
<RNCamera
style={styles.camera}
onBarCodeRead={(event) => handleScan(event)}
captureAudio={false}
/>
)}
<TouchableOpacity style={styles.button} onPress={() => setIsScanning(true)}>
<Text style={styles.buttonText}>Start Scanning</Text>
</TouchableOpacity>
{scannedData && <Text style={styles.resultText}>Scanned Data: {scannedData}</Text>}
</View>
);
};

export default ScannerScreen;

4. Start the Scanner

Add an onPress event handler to the scan button in your user interface, and call the scanning method to start capturing and processing barcode or QR code data.

By integrating a barcode and QR scanner library like react-native-camera, you can easily add scanning functionality to your React Native application.

Example Usage

<TouchableOpacity style={styles.button} onPress={() => setIsScanning(true)}>
<Text style={styles.buttonText}>Start Scanning</Text>
</TouchableOpacity>

In the above code, the pressing button is used to update the isScanning state to true. This renders the RNCamera view and starts the scanner.

5. Handle the Scanning Process

In order to capture and process barcode or QR code data in a React Native App using react-native-camera, you have to create a method like handleScan, which helps to trigger when a code is detected. This method is helpful for retrieving the scanned data from the event object. It then updates the state of the app and avoids further scanning to avoid multiple captures. This helps to keep the scanning process smooth and efficient.

Example Usage

const handleScan = (event) => {
setScannedData(event.data);
setIsScanning(false); // Stop scanning after successful scan
};

Here, the function is used to capture the scanned data from the camera, then sets the scanned data into the state so that it can be displayed. After the scanning is done, it stops the camera view.

Now, if you want to provide a better layout to this application, you also need to implement CSS to it.

Implementing Barcode Scanning Functionality

In this step, we will implement the Barcode Scanning functionality in a JavaScript/ReactNative Environment. This functionality is specifically for barcode/QR code scanning. It uses the react-native-camera and react-native-qrcode-scanner.

Simple implementation code for this functionality

import React, { Component } from 'react';
import { View, Text, StyleSheet, Alert } from 'react-native';
import { RNCamera } from 'react-native-camera';
import { QRCodeScanner } from 'react-native-qrcode-scanner';

export default class ScannerActivity extends Component {

// Handle successful scan of QR code or barcode
handleScan = (scanResult) => {
const scannedData = scanResult.data;

if (scannedData) {
// Successfully scanned barcode or QR code
this.handleScannedData(scannedData); // Process scanned data
} else {
// Handle case when scanning was cancelled
console.log('Scan was cancelled.');
}
};

// Process the scanned barcode/QR code data
handleScannedData = (data) => {
// Example: Show scanned data in an alert, or send it to a server
Alert.alert('Scanned Data', data);
console.log('Scanned Data:', data);
// You can replace this with your custom data handling logic
};

render() {
return (
<View style={styles.container}>
<QRCodeScanner
onRead={this.handleScan} // Callback when scan is successful
topContent={
<Text style={styles.centerText}>
Scan a barcode or QR code
</Text>
}
bottomContent={
<Text style={styles.centerText}>
Point the camera at the barcode or QR code.
</Text>
}
cameraProps={{
captureAudio: false, // Disable audio capture
}}
/>
</View>
);
}
}

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
centerText: {
fontSize: 18,
padding: 10,
textAlign: 'center',
},
});

Explanation

In the above code, QRCodeScanner from react-native-qrcode-scanner is used for scanning both barcodes and QR codes. 

  • After this, onRead prop is passed. It is used as a callback function after the code is successfully scanned.
  • In the next step, the handleScan method receives the scanResult object, which basically contains the scanned data of the barcode or QR code.
  • After that, the scanned data is processed and handleScannedData function is called to handle the actual processing of data, like displaying it, saving it, or sending it to a server.
  • Also, basic styles are applied to this code for centering the content and customizing the text appearance.

Enhancing the App with QR Code Scanning

Enhancing an application with QR code scanning helps users to interact with products or links through the camera. Here, you have to use the react-native-qrcode-scanner component, so that the app can capture QR codes and barcodes and then process them accordingly. 

An example code for the enhancement of the app by adding a QR code scanner is given below:

import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { RNCamera } from 'react-native-camera';
import { QRCodeScanner } from 'react-native-qrcode-scanner';

export default class QRBarcodeScanner extends Component {

// Handle successful scan of QR code or barcode
handleScan = (scanResult) => {
const scannedContent = scanResult.data;

if (scanResult.type === 'QR_CODE') {
this.handleQRCode(scannedContent); // Handle QR code data
} else {
this.handleBarcode(scannedContent); // Handle barcode data
}
};

// Handle QR code data
handleQRCode = (data) => {
// Example: Open URL or perform specific actions with QR data
console.log('QR Code Scanned:', data);
// Implement additional actions for QR code (e.g., opening a URL)
};

// Handle barcode data
handleBarcode = (data) => {
// Example: Product lookup or inventory update
console.log('Barcode Scanned:', data);
// Implement additional actions for Barcode (e.g., product details)
};

render() {
return (
<View style={styles.container}>
<QRCodeScanner
onRead={this.handleScan} // Callback on scan success
topContent={
<Text style={styles.centerText}>
Scan a Barcode or QR Code
</Text>
}
bottomContent={
<Text style={styles.centerText}>
Point the camera at the barcode or QR code.
</Text>
}
cameraProps={{
captureAudio: false, // Disable audio capture
}}
/>
</View>
);
}
}

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
centerText: {
fontSize: 18,
padding: 10,
textAlign: 'center',
},
});

Explanation

In the above code, the component QRCodeScanner is used from react-native-qrcode-scanner. This helps you to automatically handle QR and barcode scanning. The onRead event is used whenever a QR code or a barcode is scanned.

  • For handling scans, the handleScan function is used to check whether the code is a QR code or barcode and then processes the content accordingly.
  • Also, basic styles are applied to center the text and style of the content. You can also adjust them as per your requirements.

Handling Scanned Data and Displaying Results

Once the scanner successfully captures and decodes the barcode or QR code data, you will need to handle and process the result accordingly. This can involve tasks such as extracting relevant information from the scanned data, performing validations, and triggering subsequent actions based on the decoded content.

For example, if your app is used in an inventory management system, the scanned barcode may correspond to a specific product. You can then fetch the product details from a database or an API based on the scanned barcode and display relevant information to the user. An example code on how to handle scanned data and display results in an Android App after capturing a barcode or a QR code using ZXing is given below:

import React, { Component } from 'react';
import { View, Text, StyleSheet, Alert } from 'react-native';
import { QRCodeScanner } from 'react-native-qrcode-scanner';

export default class QRBarcodeScanner extends Component {

// Handle successful scan of QR code or barcode
handleScan = (scanResult) => {
const scannedContent = scanResult.data;

// Check the type of scanned code and process it accordingly
if (scanResult.type === 'QR_CODE') {
this.handleQRCode(scannedContent); // Handle QR code data
} else {
this.handleBarcode(scannedContent); // Handle barcode data
}
};

// Handle QR code data
handleQRCode = (data) => {
// Show an alert or process QR data (like opening a URL)
Alert.alert('QR Code Scanned', `Data: ${data}`, [{ text: 'OK' }]);
console.log('QR Code Scanned:', data);
};

// Handle barcode data
handleBarcode = (data) => {
// Show an alert or process barcode data (like fetching product details)
Alert.alert('Barcode Scanned', `Data: ${data}`, [{ text: 'OK' }]);
console.log('Barcode Scanned:', data);
};

render() {
return (
<View style={styles.container}>
<QRCodeScanner
onRead={this.handleScan} // Callback on scan success
topContent={
<Text style={styles.centerText}>
Scan a Barcode or QR Code
</Text>
}
bottomContent={
<Text style={styles.centerText}>
Point the camera at the barcode or QR code.
</Text>
}
cameraProps={{
captureAudio: false, // Disable audio capture
}}
/>
</View>
);
}
}

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
centerText: {
fontSize: 18,
padding: 10,
textAlign: 'center',
},
});

Explanation

  • handleScan function is used in the above code when a QR code or barcode is scanned successfully. It helps to check the type of scans and then calls the handler function, which is appropriate.
  • The functions like handleQRCode and handleBarcode are used to display the scanned data in an alert box. These functions can be customized to perform specific actions based on the type of content scanned.
  • The QRCodeScanner component is used to render the camera view and allows users to scan QR codes and barcodes. The onRead prop is also linked to the handleScan function, which helps in the processing of scanned data.

Customizing and Styling the Scanner UI

While the core functionality of barcode and QR code scanning lies in accurately capturing and decoding data, the user interface (UI) of the scanner screen plays a crucial role in providing a seamless and intuitive scanning experience.

You can customize and style the scanner UI to align with your app’s design guidelines and branding. This may involve modifying the appearance of the scanning window, adding overlays, adjusting colors, and incorporating animations to enhance the visual appeal. By providing a visually pleasing and user-friendly scanner UI, you can improve the overall user experience and engagement with your app. An example code depicting the customization and Styling of the Scanner UI is given below:

import React, { Component } from 'react';
import { View, Text, StyleSheet, Alert } from 'react-native';
import { QRCodeScanner } from 'react-native-qrcode-scanner';

export default class CustomScannerUI extends Component {

// Handle successful scan of QR code or barcode
handleScan = (scanResult) => {
const scannedContent = scanResult.data;

// Check the type of scanned code and process it accordingly
if (scanResult.type === 'QR_CODE') {
this.handleQRCode(scannedContent); // Handle QR code data
} else {
this.handleBarcode(scannedContent); // Handle barcode data
}
};

// Handle QR code data
handleQRCode = (data) => {
// Show an alert or process QR data (like opening a URL)
Alert.alert('QR Code Scanned', `Data: ${data}`, [{ text: 'OK' }]);
console.log('QR Code Scanned:', data);
};

// Handle barcode data
handleBarcode = (data) => {
// Show an alert or process barcode data (like fetching product details)
Alert.alert('Barcode Scanned', `Data: ${data}`, [{ text: 'OK' }]);
console.log('Barcode Scanned:', data);
};

render() {
return (
<View style={styles.container}>
<QRCodeScanner
onRead={this.handleScan} // Callback on scan success
topContent={
<Text style={styles.topText}>
Scan a Barcode or QR Code
</Text>
}
bottomContent={
<Text style={styles.bottomText}>
Position the camera over the barcode or QR code to scan.
</Text>
}
cameraProps={{
captureAudio: false, // Disable audio capture
}}
reactivate={true} // Reactivate scanner automatically after each scan
customMarker={ // Customizing the scanning window appearance
<View style={styles.customMarker}>
<Text style={styles.markerText}>Scan Here</Text>
</View>
}
showMarker={true} // Display a scanning marker
/>
</View>
);
}
}

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f5f5f5', // Light gray background for better contrast
},
topText: {
fontSize: 22,
fontWeight: 'bold',
textAlign: 'center',
color: '#333', // Dark text for better readability
marginBottom: 20,
},
bottomText: {
fontSize: 18,
textAlign: 'center',
color: '#666', // Lighter text for less emphasis
marginTop: 20,
},
customMarker: {
borderWidth: 2,
borderColor: '#ff5733', // Orange border for the scanning area
borderRadius: 10,
padding: 20,
backgroundColor: 'rgba(0, 0, 0, 0.3)', // Semi-transparent background
alignItems: 'center',
},
markerText: {
fontSize: 18,
fontWeight: 'bold',
color: '#ff5733', // Matching color for marker text
},
});

Explanation

  • The top and bottom contents are customizable for displaying any messages or instructions to the user. You can also adjust the text, font, size, and alignment easily.
  • The customMarker prop contains a styled border and text inside it. This indicated where the user should focus the camera for scanning the barcode or QR code.
  • The overall UI is also adjusted to fit the design guidelines. Custom colors and fonts are also added. This ensures an attractive user interface.
  • By enabling the function reactivate={true}, the scanner reactivates automatically after each scan is done. This provides smooth scanning process without the need for any manual restart.

Testing the Scanner App

Thorough testing is essential to ensure the reliability and performance of your scanner app. You should conduct both unit tests and real-world testing to validate the scanning functionality across different devices, lighting conditions, and barcode/QR code formats.

Unit tests can be performed to validate the individual components responsible for scanning, decoding, and handling the results. Additionally, real-world testing should involve scanning a variety of barcodes and QR codes in different environments to assess the accuracy and responsiveness of the scanner.

Optimizing Performance and User Experience

To deliver a smooth and efficient scanning experience, optimizing performance is crucial. There are several strategies you can employ to enhance the overall performance of your barcode and QR code scanning functionality:

  • Consider using multi-threading or asynchronous processing to prevent the scanning process from blocking the UI thread.
  • Optimize image processing algorithms to efficiently capture and decode barcodes and QR codes, ensuring faster scanning speeds.
  • Implement intelligent error handling and provide clear instructions to users in case of scanning failures or incorrect data.
  • Continuously monitor and fine-tune the performance of your scanning feature by analyzing user feedback and conducting performance profiling.

Check out other React Native resources-


Redux in React Native React Native Navigation React Native Maps
React Native Tutorial How to Use React Native Image Picker Guide to TextInput in React Native
React Native Elements React Native Environment Setup

Conclusion

Building a React Native Barcode and QR Scanner empowers developers to create powerful and versatile applications that can scan and interpret various types of barcodes and QR codes. Throughout this blog, we explored the fundamental concepts and steps required to integrate barcode and QR scanning functionality into a React Native app

By mastering the art of building a React Native Barcode and QR Scanner, developers are equipped with a valuable tool that can enhance the functionality, efficiency, and user experience of their applications.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.