react-native-qrcode-svg
を使用します。インストールにはreact-native-svgも必要なので忘れずに。
npm i react-native-qrcode-svg react-native-svg
// npx expo install react-native-qrcode-svg react-native-svg
GitHub - awesomejerry/react-native-qrcode-svg: A QR Code generator for React Native based on react-native-svg and node-qrcode.
A QR Code generator for React Native based on react-native-svg and node-qrcode. - GitHub - awesomejerry/react-native-qrcode-svg: A QR Code generator for React N...
QRコードの表示(生成)
import { StyleSheet, Text, View } from 'react-native';
import QRCode from 'react-native-qrcode-svg';
export default function App() {
return (
<View style={styles.container}>
<Text>QRコード</Text>
<QRCode
value='アヒル'
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});

QRコードを保存
QR画像の保存に別途、expo-file-system
と expo-media-library
が必要なのでインストールしてください。
QRコードの画像データはgetRef
とtoDataURL
を使用することで利用できます。
画像データは文字列で、base64でエンコードされているので、FileSystem.writeAsStringAsync
のエンコーディングをbase64に設定しましょう。
import { Button, StyleSheet, Text, View, Alert } from 'react-native';
import QRCode from 'react-native-qrcode-svg';
import { useRef } from 'react';
import * as FileSystem from 'expo-file-system';
import * as MediaLibrary from 'expo-media-library';
export default function App() {
const svg = useRef('');
const saveUrl = FileSystem.documentDirectory + 'qrcode.png';
return (
<View style={styles.container}>
<Text>QRコード</Text>
<QRCode
value='アヒル'
getRef={svg}
/>
<Button
title='QRコードの保存'
onPress={()=>{
svg.current.toDataURL(async (data)=>{
// 一旦ドキュメントディレクトリに保存する
await FileSystem.writeAsStringAsync(saveUrl, data, {encoding: 'base64'})
// ドキュメントディレクトリのURLを指定して、メディアライブラリに保存
await MediaLibrary.saveToLibraryAsync(saveUrl);
Alert.alert('QRコードを保存しました')
})
}}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
コメント