How to build a QR and Bar Code Reader using React Native
August 05, 2021
How to build a QR and Bar Code Reader using React Native
Getting Started
Let’s start a new RN application:
react-native init BitFritScan && cd BitFritScan
Now, we’ll need to install the following libraries in order to build our app:
First Just Follow the Docs : https://www.npmjs.com/package/react-native-qrcode-scanner
If you see aNo permission handler detected error in iOS:
Try this by adding the permissions_path with Permission-Camera
ios/Podfile
platform :ios, '10.0'
target 'AwesomeProject' do
permissions_path = '../node_modules/react-native-permissions/ios'
pod 'Permission-Camera', :path => "#{permissions_path}/Camera"
config = use_native_modules!
Then update yourInfo.plist
with wanted permissions usage descriptions:
<key>NSCameraUsageDescription</key>
<string>Our app need your permission to use your camera phone</string>
Then cd ios and run pod install it will install permission
Scan.js
import React, {useEffect, useState} from 'react';
import { AuthHeader } from '../../Componets'
import styled from 'styled-components/native';
import GlobalStyles from '../../Componets/GlobalStyles';
import QRCodeScanner from 'react-native-qrcode-scanner';
import { RNCamera } from 'react-native-camera';
import Xml2js from 'react-native-xml2js';
import { StyleSheet,Text,TouchableOpacity } from 'react-native';
const Scan = ({navigation}) => {
const [Data, SetData] = useState(null);
const onSuccess = e => {
const {type,data}=e;
if(type==="QR_CODE"){
let parser = new Xml2js.Parser();
parser.parseString(data, (err, result)=> {
console.info(result)
SetData(result)
})
}else{
console.info(e)
SetData(data)
}
}
useEffect(() => {
const onBlur = navigation.addListener('blur', () => {
SetData(null)
});
return {onBlur};
}, [navigation]);
return (
<Container style={GlobalStyles.droidSafeArea}>
<AuthHeader Title={'Scan'} navigation={navigation}/>
<ContainerMain>
{Data?
<Text style={styles.centerText}>
{JSON.stringify(Data)}
</Text>:
<QRCodeScanner
onRead={onSuccess}
reactivate={true}
flashMode={RNCamera.Constants.FlashMode.torch}
topContent={
<Text style={styles.centerText}>
Go to{' '}
<Text style={styles.textBold}>wikipedia.org/wiki/QR_code</Text> on
your computer and scan the QR code.
</Text>
}
bottomContent={
<TouchableOpacity style={styles.buttonTouchable}>
<Text style={styles.buttonText}>OK. Got it!</Text>
</TouchableOpacity>
}
/>
}
</ContainerMain>
</Container>
)
}
const styles = StyleSheet.create({
centerText: {
flex: 1,
fontSize: 18,
padding: 32,
color: '#777'
},
textBold: {
fontWeight: '500',
color: '#000'
},
buttonText: {
fontSize: 21,
color: 'rgb(0,122,255)'
},
buttonTouchable: {
padding: 16,
}
});
const Container = styled.SafeAreaView`
flex: 1;
background-color: #343434;
`;
const ContainerMain = styled.View`
flex: 1;
background-color: #ffffff;
`;
export default Scan;