Sharing the image

Similar to expo-image-picker, the functionality that we need to share is available in an Expo library this one is called expo-sharing.

You can install expo-sharing in the same way as you installed expo-image-picker:
  • Run expo install expo-sharing in your project directory.

import React from 'react';
import { Image, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import * as Sharing from 'expo-sharing';

export default function App() {
  const [selectedImage, setSelectedImage] = React.useState(null);

  let openImagePickerAsync = async () => {
    /* most contents of this function were hidden here to keep the example brief */

    setSelectedImage({ localUri: pickerResult.uri });
  };

  let openShareDialogAsync = async () => {
    if (!(await Sharing.isAvailableAsync())) {
      alert(`Uh oh, sharing isn't available on your platform`);
      return;
    }

    Sharing.shareAsync(selectedImage.localUri);
  };

  if (selectedImage !== null) {
    return (
      <View style={styles.container}>
        <Image source={{ uri: selectedImage.localUri }} style={styles.thumbnail} />

        <TouchableOpacity onPress={openShareDialogAsync} style={styles.button}>
          <Text style={styles.buttonText}>Share this photo</Text>
        </TouchableOpacity>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      {/* Our logo, instructions, and picker button are hidden here to keep the example brief */}
    </View>
  );
}

🥰 Everything is working great! The operating system share dialog opens up and is ready to share our selected image.

😱 Uh oh. When we hit "Share this photo" we see that our alert warns us that sharing is not available. This is happening because the desktop Chrome browser does not currently provide a way for users to share content.

Want to learn more about why we can't use expo-sharing in Chrome?

Sharing didn't work here because the desktop Chrome browser doesn't yet implement the Web Share API. "But wait," you say, "aren't we using expo-sharing, not the Web Share API?" You can you can think of the Expo SDK libraries as translators for different platforms. They speak the language of Expo and turn it into the language of iOS, Android, and web. It isn't always possible to translate from Expo's language to the platform that you're working with. In other words, if the platform doesn't implement a feature, Expo can't tell it to invoke that feature. In some cases Expo can attempt to polyfill the feature for you, but this isn't always possible. Invoking your operating system's built-in share dialog to share content with other applications needs to be implemented by the platform itself Chrome in this case.

In the next section we are going to look at how we can handle this and another important platform difference. Continue to "Handling platform differences".