React Native QR Scanner Example
Jun 28, 2022 . Admin
Hi Guys,
Here, I will show you how to works how to create barcode scanner in react native. This tutorial will give you simple example of how to use barcode scanner in react native. you will learn how to implement barcode scanner in react native. step by step explain react native barcode scanner example. you will do the following things for barcode scanner example in react native.
Let's start following example:
Step 1: Download ProjectIn the first step run the following command to create a project.
expo init ExampleAppStep 2: Install and Setup
You install expo-barcode-scanner to create barcode scanner:
expo install expo-barcode-scannerStep 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...