A Step-by-Step Guide to Share images from Your Expo React Native App to Instagram Stories
Tags: reactnative, expo, instagram, mobile
Published: 2023-02-28 16:18:24

Let's get started with this step-by-step guide to share images from your Expo React Native App to Instagram Stories! With this guide, you will be able to easily install the necessary libraries - react-native-view-shot and react-native-share - and create a component with the example code. I also share some tips for debugging if you get stuck and a few resources to help you out. So, let's get started!

## Steps

### Step 1: Create an expo app or open an existing expo-managed app

```bash
npx create-expo-app my-app && cd my-app
```

### Step 2: Install the following mentioned libraries:


1. [react-native-view-shot](https://www.npmjs.com/package/react-native-view-shot) - to capture a React Native View as an image.

2. [react-native-share](https://www.npmjs.com/package/react-native-share) - to share the captured image as a sticker to your Instagram stories.

### Step 3: Copy the following example code as a component

> Ps: I've tried to explain as much as I can within the code snippet below, if there are still any questions, please feel free to ask!

```js
import { useRef, useState, useEffect } from 'react';
import { Text, View, Button, Platform, Linking } from "react-native";
import { captureRef } from "react-native-view-shot";
import Share from "react-native-share";

const App = () => {
    const viewRef = useRef(null); // ref used to mark the View to be screenshotted 📸, check the returned JSX below

    const [hasInstagramInstalled, setHasInstagramInstalled] = useState(false); // State to track if Instagram is installed on user's device or not
    
    useEffect(() => {
        if (Platform.OS === "ios") {
// If platform is IOS then check if instagram is installed on the user's device using the `Linking.canOpenURL` API
          Linking.canOpenURL("instagram://").then((val) =>
            setHasInstagramInstalled(val),
          );
        } else {
// Else check on android device if instagram is installed in user's device using the `Share.isPackageInstalled` API
          Share.isPackageInstalled("com.instagram.android").then(
            ({ isInstalled }) => setHasInstagramInstalled(isInstalled),
          );
        }
    }, []);

    async function captureAndShare() {
        try {
          // Capture the screenshot of the element and store it into the uri variable
          const uri = await captureRef(viewRef, {
            format: "png",
            quality: 1,
          });
    
          if (hasInstagramInstalled) {
            await Share.shareSingle({
              appId: "", // Note: replace this with your own appId from facebook developer account, it won't work without it. (https://developers.facebook.com/docs/development/register/)
              stickerImage: uri,
              social: Share.Social.INSTAGRAM_STORIES,
              backgroundBottomColor: "#1D1D1D", // You can use any hexcode here and below
              backgroundTopColor: "#1D1D1D",
              backgroundImage: '...', // This field is optional like the other fields (except appId) and you have to put a base64 encoded image here if you want to use it!
            });
          } else {
            // If instagram is not installed in user's device then just share using the usual device specific bottomsheet (https://react-native-share.github.io/react-native-share/docs/share-open)
            await Share.open({ url: uri });
          }
        } catch (error) {
          console.error(error);
        }
      }    

    return (
            <>
                <View ref={viewRef}>
                    <Text style={{ color: "red" }}>Hello world!</Text>
                </View>

                <Button 
                   onPress={captureAndShare} 
                   title='Capture & Share'
                />
            </>
        )
}

export default App;
```

> Note: for testing react-native-share's functionality in your expo managed app, you will have to make use of [Expo development builds](https://docs.expo.dev/development/introduction/).

## Tips for debugging if stuck

1. APIs from various packages and Instagram are ever-changing, hence if you are stuck, I would highly recommend to go and search in their GitHub issues and PRs tab, it's very likely that someone has already faced it. I would also be happy to help you out if that doesn't work out 😇

2. Make sure that you test on both IOS and Android devices before releasing as there might be some things that don't work across platforms and you might need to handle them.

## Resources

1. [Sharing to Stories](https://developers.facebook.com/docs/instagram/sharing-to-stories) - Facebook docs for sharing from apps to stories, it does not have anything specific to react-native or expo, but it's a must-read to understand the API and values it accepts.

2. [Create an image from a React Native component and share it on social media](https://www.youtube.com/watch?v=3HkHDjLkqRo&t=733s&ab_channel=JimmyCook) - This video is a little old but it gives you a good idea of the problem and the solution.

3. [What are development builds and how to set them up](https://docs.expo.dev/development/introduction/) - comprehensive, complete, and up-to-date docs from the expo team. [[Video alternative]](https://www.youtube.com/watch?v=id0Im72UN6w&t=441s&ab_channel=Expo)