react nativeでQR画像の表示と保存

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. - awesomejerry/react-native-qrcode-svg

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-systemexpo-media-library が必要なのでインストールしてください。

QRコードの画像データはgetReftoDataURLを使用することで利用できます。
画像データは文字列で、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',
  },
});

コメント