Share text string using expo-sharing
Asked Answered
A

1

5

I'm trying to use Share dialog to share a piece of text on Expo. Though from the current documentation I cannot find anything related to this.

Right now, my workaround is saving the text as .txt to user's device and sharing that. But surely there must be a better way-- even iOS has a native way of doing it. But how do I implement something similar with Expo's expo-sharing package?

My current workaround (modified for brevity):

import * as Sharing from 'expo-sharing';
import * as FileSystem from 'expo-file-system';

...


  const shareText = async (text) => {
    if (!await Sharing.isAvailableAsync()) {
        alert("Sharing is not available on this platform");
        return;
    }

    const fileName = FileSystem.documentDirectory + "text"+new Date().getDate()+"-"+new Date().getMonth()+"-"+new Date().getFullYear()+"_"+new Date().getHours()+"-"+new Date().getMinutes()+".txt";
    await FileSystem.writeAsStringAsync(fileName, text);

    try {
        await Sharing.shareAsync(fileName);
    } catch (error) {
        console.error("Failed sharing: ", error.message);
    }
};
Archivolt answered 12/9, 2023 at 2:47 Comment(0)
A
18

Update: Its possible using React Native share. Works fine in Expo.

import { Share } from 'react-native';

...

const shareText = async (text) => {
    try {
        await Share.share({
            message: text
        });
    } catch (error) {
        console.error('Error sharing:', error);
    }
};

Archivolt answered 12/9, 2023 at 11:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.