How to Create Barcode Scanner in React Native?

04-Apr-2023

.

Admin

How to Create Barcode Scanner in React Native?

Hi Guys,

Today, react native barcode scanner example is our main topic. if you have question about how to implement barcode scanner in react native then I will give simple example with solution. This post will give you simple example of how to use barcode scanner in react native. it's simple example of barcode scanner example in react native. So, let's follow few step to create example of how to create barcode scanner in react native.

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...

#React Native