STEP1 : ライブラリのインストール
React Native(Expo)でQRコードを読み取るには expo-barcode-scanner
を使用します。

BarCodeScanner - Expo Documentation
Expo is an open-source platform for making universal native apps for Android, iOS, and the web with JavaScript and React.
まずは expo-barcode-scanner
をインストールしましょう。
npx expo install expo-barcode-scanner
STEP2 : QRコードスキャナを使ってみよう
前提知識1 : カメラの使用許可を取得する
カメラの使用許可は usePermissions
というフックで取得ができます。
import { usePermissions } from 'expo-barcode-scanner'
const [ permission, requestPermission] = usePermissions()
permission
には許可のステータスが格納されています。
canAskAgain
expires
granted
status
がありますが、今回はgranted
を使用します。granted
はカメラの使用が許可されているかを表します。
そして、requestPermission
で許可をユーザーにお願い🙇♂️することが可能です。

BarCodeScanner - Expo Documentation
Expo is an open-source platform for making universal native apps for Android, iOS, and the web with JavaScript and React.
前提知識2 : QRスキャナーのコンポーネント
QRスキャナー(カメラ画面)のコンポーネントは
import { BarCodeScanner } from 'expo-barcode-scanner';
<BarCodeScanner />
のようにして使います。
今回はprops
として
barCodeTypes
: スキャンするバーコードのタイプ(今回はQRコード)onBarCodeScanned
: スキャンした時の挙動
を使ってみます。

BarCodeScanner - Expo Documentation
Expo is an open-source platform for making universal native apps for Android, iOS, and the web with JavaScript and React.
実装してみる
コードはこのようになりました。
重要な箇所だけ解説します。
まず、8行目と35行目で許可状況に応じて表示する内容を変えているのは、許可されていなければカメラが映らないからです。また、許可されていない場合では許可を申請できるようにボタンを配置してあります。
そして13行目の onBarCodeScanned
で条件分けをしているのは、QRコードを写している時はずっ〜と onBarCodeScanned
が繰り返し実行されるので、この場合だとalert
が大量発生してしまうからです。
import { StyleSheet, Button, View, Alert } from 'react-native';
import { BarCodeScanner, usePermissions } from 'expo-barcode-scanner';
export default function App() {
const [ permission, requestPermission ] = usePermissions();
let scanning = false
if(permission?.granted){
return (
<View style={styles.container}>
<BarCodeScanner
barCodeTypes={[BarCodeScanner.Constants.BarCodeType.qr]}
onBarCodeScanned={(scannerResult)=>{
if(scanning){
}
else{
scanning = true
Alert.alert(
"スキャン結果",
scannerResult.data,
[
{
text: '閉じる',
onPress: ()=>{scanning=false}
}
]
)
}
}}
style={styles.barCodeScanner}
/>
</View>
)
}
else{
return (
<View style={styles.container}>
<Button
title="カメラを開く"
onPress={requestPermission}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
barCodeScanner: {
height: '100%',
width: '100%'
}
});
STEP3 : QRスキャナーの動作確認

コメント