ReactNative Scan QR code
To implement QR code scanning in a React Native app, you can use the react-native-camera
library. This library provides a simple way to access the device's camera and handle QR code scanning. Here's a step-by-step guide:
Install react-native-camera
npm install react-native-camera
Permissions (for Android)
Ensure that you have the necessary camera permissions. In your AndroidManifest.xml:
<uses-permission android:name="android.permission.CAMERA" />
Code Implementation
import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { RNCamera } from 'react-native-camera';
const QRCodeScanner = () => {
const [scanned, setScanned] = useState(false);
const handleBarCodeScanned = ({ data }) => {
setScanned(true);
alert(`Scanned QR Code: ${data}`);
};
useEffect(() => {
return () => {
// Clean up any resources or listeners when the component unmounts
};
}, []);
return (
<View style={{ flex: 1 }}>
<RNCamera
style={{ flex: 1 }}
onBarCodeRead={scanned ? undefined : handleBarCodeScanned}
barCodeTypes={[RNCamera.Constants.BarCodeType.qr]}
>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'flex-end',
}}
>
<TouchableOpacity
style={{
padding: 16,
backgroundColor: 'white',
borderRadius: 8,
}}
onPress={() => setScanned(false)}
>
<Text style={{ fontSize: 18, color: 'black' }}>Scan Again</Text>
</TouchableOpacity>
</View>
</RNCamera>
</View>
);
};
export default QRCodeScanner;
In this example, the RNCamera
component is used to access the device's camera.
When a QR code is successfully scanned, the handleBarCodeScanned
the function is called, and the scanned data is displayed in an alert. You can customize the UI and handling logic based on your application's requirements.