DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • How to Build a React Native Chat App for Android
  • Optimizing User Experience in React Native
  • Cross-Platform Mobile Application Development: Evaluating Flutter, React Native, HTML5, Xamarin, and Other Frameworks

Trending

  • Optimizing Serverless Computing with AWS Lambda Layers and CloudFormation
  • Useful System Table Queries in Relational Databases
  • Bridging UI, DevOps, and AI: A Full-Stack Engineer’s Approach to Resilient Systems
  • How to Use AWS Aurora Database for a Retail Point of Sale (POS) Transaction System
  1. DZone
  2. Coding
  3. JavaScript
  4. React Native QR Code Scanner Using Expo-Barcode-Scanner

React Native QR Code Scanner Using Expo-Barcode-Scanner

By 
Kunkka Li user avatar
Kunkka Li
·
Sep. 30, 20 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
18.6K Views

Join the DZone community and get the full member experience.

Join For Free

QR codes are usually used as a URL locator for applications, such as mobile payment. In this post, I will walk you through how to implement a mobile QR code scanner with React Native, along with a cool expo library. This post will help you learn how to:

  • How to implement a QR code scanner using React Native and TypeScript.
  • How to limit the QR code detecting area.
  • How to add a mask scanning area.
  • How to debug react native app by using expo client.

The code is written with Typescript and is available in Github: 

https://github.com/liqili/react-native-qrcode-scanner

Before starting, you need to install Node.js development environment and Yarn package management tool. Then install expo client to your mobile phone from ios app store or google play store.

Installing Expo CLI and Init Project

Java
 




xxxxxxxxxx
1


 
1
npm install --global expo-cli
2
expo init react-native-qrcode-scanner
3
yarn install
4
expo eject //run this if you want to publish with bare workflow(ios/android)
5
expo start


Screen page for QR code scanning

JavaScript
 




xxxxxxxxxx
1
95


 
1
import React, {useEffect, useState} from 'react';
2
import {Button, Dimensions, StyleSheet, TouchableOpacity} from 'react-native';
3
import {Text, View} from '../components/Themed';
4
import {BarCodeScanner, BarCodeScannerResult} from 'expo-barcode-scanner';
5
import BarcodeMask from 'react-native-barcode-mask';
6

          
7
const finderWidth: number = 280;
8
const finderHeight: number = 230;
9
const width = Dimensions.get('window').width;
10
const height = Dimensions.get('window').height;
11
const viewMinX = (width - finderWidth) / 2;
12
const viewMinY = (height - finderHeight) / 2;
13

          
14

          
15
export default function BarCodeScanScreen() {
16
    const [hasPermission, setHasPermission] = useState<boolean | null>(null);
17
    const [type, setType] = useState<any>(BarCodeScanner.Constants.Type.back);
18
    const [scanned, setScanned] = useState<boolean>(false);
19

          
20

          
21
    useEffect(() => {
22
        (async () => {
23
            const {status} = await BarCodeScanner.requestPermissionsAsync();
24
            setHasPermission(status === 'granted');
25
        })();
26
    }, []);
27

          
28
    const handleBarCodeScanned = (scanningResult: BarCodeScannerResult) => {
29
        if (!scanned) {
30
            const {type, data, bounds: {origin} = {}} = scanningResult;
31
            // @ts-ignore
32
            const {x, y} = origin;
33
            if (x >= viewMinX && y >= viewMinY && x <= (viewMinX + finderWidth / 2) && y <= (viewMinY + finderHeight / 2)) {
34
                setScanned(true);
35
                alert(`Bar code with type ${type} and data ${data} has been scanned!`);
36
            }
37
        }
38
    };
39

          
40
    if (hasPermission === null) {
41
        return <Text>Requesting for camera permission</Text>;
42
    }
43
    if (hasPermission === false) {
44
        return <Text>No access to camera</Text>;
45
    }
46
    return (
47
        <View style={{flex: 1}}>
48
            <BarCodeScanner onBarCodeScanned={handleBarCodeScanned}
49
                            type={type}
50
                            barCodeTypes={[BarCodeScanner.Constants.BarCodeType.qr]}
51
                            style={[StyleSheet.absoluteFillObject, styles.container]}>
52
                <View
53
                    style={{
54
                        flex: 1,
55
                        backgroundColor: 'transparent',
56
                        flexDirection: 'row',
57
                    }}>
58
                    <TouchableOpacity
59
                        style={{
60
                            flex: 1,
61
                            alignItems: 'flex-end',
62
                        }}
63
                        onPress={() => {
64
                            setType(
65
                                type === BarCodeScanner.Constants.Type.back
66
                                    ? BarCodeScanner.Constants.Type.front
67
                                    : BarCodeScanner.Constants.Type.back
68
                            );
69
                        }}>
70
                        <Text style={{fontSize: 18, margin: 5, color: 'white'}}> Flip </Text>
71
                    </TouchableOpacity>
72
                </View>
73
                <BarcodeMask edgeColor="#62B1F6" showAnimatedLine/>
74
                {scanned && <Button title="Scan Again" onPress={() => setScanned(false)}/>}
75
            </BarCodeScanner>
76
        </View>
77
    );
78
}
79

          
80
const styles = StyleSheet.create({
81
    container: {
82
        flex: 1,
83
        alignItems: 'center',
84
        justifyContent: 'center',
85
    },
86
    title: {
87
        fontSize: 20,
88
        fontWeight: 'bold',
89
    },
90
    separator: {
91
        marginVertical: 30,
92
        height: 1,
93
        width: '80%',
94
    },
95
});


Add a Mask Area

JavaScript
 




xxxxxxxxxx
1


 
1
import BarcodeMask from 'react-native-barcode-mask';
2
/*
3
*
4
*
5
*/
6
<BarcodeMask edgeColor="#62B1F6" showAnimatedLine/>



Limit detecting area

In some cases, if you don't want to scan the whole camera area, we can handle this in the callback method.

JavaScript
 




xxxxxxxxxx
1
11


 
1
const finderWidth: number = 280;
2
const finderHeight: number = 230;
3
const width = Dimensions.get('window').width;
4
const height = Dimensions.get('window').height;
5
const viewMinX = (width - finderWidth) / 2;
6
const viewMinY = (height - finderHeight) / 2;
7

          
8
if (x >= viewMinX && y >= viewMinY && x <= (viewMinX + finderWidth / 2) && y <= (viewMinY + finderHeight / 2)) {
9
    setScanned(true);
10
    alert(`Bar code with type ${type} and data ${data} has been scanned!`);
11
}



Then you are all set!

Scanning a QR Code


QR code React Native React (JavaScript library)

Opinions expressed by DZone contributors are their own.

Related

  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • How to Build a React Native Chat App for Android
  • Optimizing User Experience in React Native
  • Cross-Platform Mobile Application Development: Evaluating Flutter, React Native, HTML5, Xamarin, and Other Frameworks

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!