How to Implement Barcode Scanner in React Native?

Published On: 28/06/2022 | Category: React Native

Hi Guys,

This simple article demonstrates of how to use barcode scanner in react native. This tutorial will give you simple example of how to create barcode scanner in react native. I would like to share with you how to implement barcode scanner in react native. let’s discuss about barcode scanner example in react native. Let's see bellow example react native barcode scanner example.

Let's start following example:

Step 1: Download Project

In the first step run the following command to create a project.

expo init ExampleApp
Step 2: Install and Setup

You install expo-barcode-scanner to create barcode scanner:

expo install expo-barcode-scanner
Step 3: App.js

In this step, You will open the App.js file and put the code.

import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';

const App = () => {
    const [hasPermission, setHasPermission] = useState(null);
    const [scanned, setScanned] = useState(false);
    const [text, setText] = useState('Not Yet Scanned');

    useEffect(() => {
        (async () => {
            const { status } = await BarCodeScanner.requestPermissionsAsync();
            setHasPermission(status === 'granted');
        })();
    }, []);

    const handleBarCodeScanned = ({ type, data }) => {
        setScanned(true);
        setText(data);
        alert(`Bar code with type ${type} and data ${data} has been scanned!`);
    };

    if (hasPermission === null) {
        return <Text>Requesting for camera permission</Text>;
    }

    if (hasPermission === false) {
        return <Text>No access to camera</Text>;
    }

    return (
        <View style={styles.container}>
            <View style={styles.barcodBox}>
                <BarCodeScanner
                    onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
                    style={{ height: 400, width: 400 }}
                />
                <Text style={styles.mainText}>{text}</Text>
                {scanned &&
                    <Button
                        title='scan again'
                        onPress={() => setScanned(false)}
                    />
                }
            </View>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
    },
    barcodBox: {
        justifyContent: 'center',
        alignItems: 'center',
        height: 300,
        width: 400,
        borderRadius: 30,
    },
    mainText: {
        fontSize: 16,
        margin: 20,
    },
});

export default App;
Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output :

It will help you...