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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Hand-Rolling Chat UIs: Streaming LLM Tokens Into React Native Without the Jank
  • Stop React Native Crashes: A Production-Ready Error Handling Guide
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • How to Build a React Native Chat App for Android

Trending

  • Why AI Agents Need a Shared Enterprise Ontology
  • Share Delta Lake Tables Between Databricks and Snowflake
  • Deploying Small Language Models on Sovereign Cloud
  • Replay, Scheduling, and Throttling: Engineering a Self-Service Kafka Streaming Tool at Scale

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Sep. 30, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
20.0K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Stop Hand-Rolling Chat UIs: Streaming LLM Tokens Into React Native Without the Jank
  • Stop React Native Crashes: A Production-Ready Error Handling Guide
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • How to Build a React Native Chat App for Android

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook