Implementing Social Media Sharing in React Native

In this comprehensive guide, we'll explore various methods to implement social media sharing in React Native applications, covering both native sharing capabilities and platform-specific integrations.

July 18, 20243 min read

The emergence of Social media sharing is a crucial feature for many mobile applications, there’s also a rise in social media applications that businesses use to reach their wider audiences as the application becomes bigger. In this article, we’ll explore various methods of implementing social media sharing in React Native applications both Native and and platform-specific.

Using React Native's Share API

React Native provides a built-in Share API which allows you to access native sharing capabilities of both iOS and Android. With this way, it’s the simplest method of enabling social media sharing capabilities on your React Native application

Here is an example of how to use the Share API provided by expo:

Image
import React from 'react';
import {Alert, Share, View, Button} from 'react-native';

const ShareExample = () => {
  const onShare = async () => {
    try {
      const result = await Share.share({
        message:
          'React Native | A framework for building native apps using React',
      });
      if (result.action === Share.sharedAction) {
        if (result.activityType) {
          // shared with activity type of result.activityType
        } else {
          // shared
        }
      } else if (result.action === Share.dismissedAction) {
        // dismissed
      }
    } catch (error) {
      Alert.alert(error.message);
    }
  };
  return (
    <View style={{marginTop: 50}}>
      <Button onPress={onShare} title="Share" />
    </View>
  );
};

export default ShareExample;

This example demonstrates a simple share button that, when pressed, opens the native share dialog with a message. The example has been derived from the react native documentation

Implementing Platform-Specific Sharing

While the Share API is convenient, you might want more control over sharing your content on specific platforms. Let's explore how to implement sharing for some popular social media platforms.

Try Kodaschool for free

Click below to sign up and get access to free web, android and iOs challenges.

Sign Up

Twitter Sharing

For Twitter, you can use deep linking to open the Twitter app with a pre-filled tweet. Here's an example:

Image
import React from 'react';
import { Button, Linking } from 'react-native';

const shareOnTwitter = async () => {
        const message = encodeURIComponent('Check out this awesome articles on React Native');
        const url = encodeURIComponent('https://kodaschool.com/category/react-native');
        const twitterUrl = `twitter://post?message=${message}&url=${url}`;
        const webUrl = `https://twitter.com/intent/tweet?text=${message}&url=${url}`;
        try {
            const supported = await Linking.canOpenURL(twitterUrl);
            if (supported) {
                await Linking.openURL(twitterUrl);
            } else {
                await Linking.openURL(webUrl);
            }
        } catch (error) {
            console.error('Error sharing to Twitter:', error);
        }
    }

LinkedIn Sharing

LinkedIn sharing can be implemented using their mobile SDK or through deep linking:

import React from 'react';
import { Button, Linking } from 'react-native';

// Share on Linked In
    const shareOnLinkedIn = async () => {
        const message = encodeURIComponent('Check out this awesome articles on React Native from an Expo App to Linked In');
        const url = encodeURIComponent('https://kodaschool.com/category/react-native');
        const linkedInUrl = `https://www.linkedin.com/sharing/share-offsite/?message=${message}&url=${url}`;
        const webUrl = `https://www.linkedin.com/sharing/share-offsite/?text=${message}&url=${url}`;
        try {
            const supported = await Linking.canOpenURL(linkedInUrl);
            if (supported) {
                await Linking.openURL(linkedInUrl);
            } else {
                await Linking.openURL(webUrl);
            }
        } catch (error) {
            console.error('Error sharing to Twitter:', error);
        }
    }

export default LinkedInShareExample;
Image

Using Third-Party Libraries for Social Sharing

Several third-party libraries are available that simplify the process of implementing social media sharing across multiple platforms. One popular library is react-native-share. This however only supports platform-specific using React Native CLI and does not work with expo Go App

First, install the library:

npm install react-native-share

Then, you can use it like this:

import { Button, Text, View } from 'react-native'

import Share from 'react-native-share';

// Share using 3rd Party React Native Share Library



const socialsharinglib = () => {
    const onShare = async () => {
        const options = {
            message: 'Check out this awesome app!',
            url: 'https://your-app-url.com',
            title: 'App Link'
        };

        try {
            const ShareResponse = await Share.open(options);
            console.log(JSON.stringify(ShareResponse));
        } catch (error) {
            console.log('Error =>', error);
        }
    };

    return (
        <View>
            <Button onPress={onShare} title="Share" />
        </View>
    )
}


export default socialsharinglib
Image

This library provides a unified interface for sharing across different platforms and includes additional features like custom share sheets.https://react-native-share.github.io/react-native-share/docs/install

Custom Share Dialogs

Sometimes, you might want to create a custom share dialog to match your app's design or to provide a more tailored sharing experience. In the code snippet below we create a custom modal where all the share buttons are put to showcase how to add a custom dialog.

const CustomShareModal: React.FC<CustomShareModalProps> = ({ visible, onClose, onShare, onShareTwitter, onShareLinkedIn }) => {
    return (
        <Modal
            animationType="slide"
            transparent={true}
            visible={visible}
            onRequestClose={onClose}
        >
            <View style={styles.centeredView}>
                <View style={styles.modalView}>
                    <Text style={styles.modalText}>Share via</Text>
                    <TouchableOpacity style={styles.button} onPress={onShare}>
                        <Text style={styles.buttonText}>React Native Share API</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.button} onPress={onShareTwitter}>
                        <Text style={styles.buttonText}>Share on X.com</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.button} onPress={onShareLinkedIn}>
                        <Text style={styles.buttonText}>Share on LinkedIn</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={[styles.button, styles.buttonClose]} onPress={onClose}>
                        <Text style={styles.buttonText}>Close</Text>
                    </TouchableOpacity>
                </View>
            </View>
        </Modal>
    );
};
Image

You can then use this custom dialog in your main component:

import React, { useState } from 'react';
import { Button, View } from 'react-native';
import CustomShareDialog from './CustomShareDialog';

const App = () => {
  const [visible, setVisible] = useState(false);

  const handleShare = (platform) => {
    // Implement platform-specific sharing here
    console.log(`Sharing to ${platform}`);
    setVisible(false);
  };

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Button title="Share" onPress={() => setVisible(true)} />
      <CustomShareDialog 
        visible={visible} 
        onClose={() => setVisible(false)} 
        onShare={handleShare} 
      />
    </View>
  );
};

export default App;

Full page Code

With all that we have learnt today, here's the full code

Image
import { Alert, Button, Linking, Modal, Share, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import React, { useState } from 'react';

interface CustomShareModalProps {
    visible: boolean;
    onClose: () => void;
    onShare: () => Promise<void>;
    onShareTwitter: () => Promise<void>;
    onShareLinkedIn: () => Promise<void>;
}

const CustomShareModal: React.FC<CustomShareModalProps> = ({ visible, onClose, onShare, onShareTwitter, onShareLinkedIn }) => {
    return (
        <Modal
            animationType="slide"
            transparent={true}
            visible={visible}
            onRequestClose={onClose}
        >
            <View style={styles.centeredView}>
                <View style={styles.modalView}>
                    <Text style={styles.modalText}>Share via</Text>
                    <TouchableOpacity style={styles.button} onPress={onShare}>
                        <Text style={styles.buttonText}>React Native Share API</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.button} onPress={onShareTwitter}>
                        <Text style={styles.buttonText}>Share on X.com</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.button} onPress={onShareLinkedIn}>
                        <Text style={styles.buttonText}>Share on LinkedIn</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={[styles.button, styles.buttonClose]} onPress={onClose}>
                        <Text style={styles.buttonText}>Close</Text>
                    </TouchableOpacity>
                </View>
            </View>
        </Modal>
    );
};

const SocialSharing: React.FC = () => {
    const [modalVisible, setModalVisible] = useState<boolean>(false);

    const onShare = async (): Promise<void> => {
        try {
            const result = await Share.share({
                message: 'React Native | A framework for building native apps using React',
                title: 'React Native Share API | Article from KodaSchool',
            });
            if (result.action === Share.sharedAction) {
                if (result.activityType) {
                    // shared with activity type of result.activityType
                } else {
                    // shared
                }
            } else if (result.action === Share.dismissedAction) {
                // dismissed
            }
        } catch (error: any) {
            Alert.alert(error.message);
        }
    };

    const shareOnTwitter = async (): Promise<void> => {
        const message = encodeURIComponent('Check out this awesome articles on React Native Expo App to x');
        const url = encodeURIComponent('https://kodaschool.com/category/react-native');
        const twitterUrl = `twitter://post?message=${message}&url=${url}`;
        const webUrl = `https://twitter.com/intent/tweet?text=${message}&url=${url}`;
        try {
            const supported = await Linking.canOpenURL(twitterUrl);
            if (supported) {
                await Linking.openURL(twitterUrl);
            } else {
                await Linking.openURL(webUrl);
            }
        } catch (error) {
            console.error('Error sharing to Twitter:', error);
        }
    }

    const shareOnLinkedIn = async (): Promise<void> => {
        const message = encodeURIComponent('Check out this awesome articles on React Native from an Expo App to Linked In');
        const url = encodeURIComponent('https://kodaschool.com/category/react-native');
        const linkedInUrl = `https://www.linkedin.com/sharing/share-offsite/?message=${message}&url=${url}`;
        try {
            await Linking.openURL(linkedInUrl);
        } catch (error) {
            console.error('Error sharing to LinkedIn:', error);
        }
    }

    return (
        <View style={styles.container}>
            <Button onPress={() => setModalVisible(true)} title="Open Share Dialog" />
            <CustomShareModal
                visible={modalVisible}
                onClose={() => setModalVisible(false)}
                onShare={onShare}
                onShareTwitter={shareOnTwitter}
                onShareLinkedIn={shareOnLinkedIn}
            />
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    centeredView: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
    },
    modalView: {
        margin: 20,
        backgroundColor: 'white',
        borderRadius: 20,
        padding: 35,
        alignItems: 'center',
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2,
        },
        shadowOpacity: 0.25,
        shadowRadius: 4,
        elevation: 5,
    },
    button: {
        borderRadius: 20,
        padding: 10,
        elevation: 2,
        backgroundColor: '#2196F3',
        marginVertical: 10,
    },
    buttonClose: {
        backgroundColor: '#FF6347',
    },
    buttonText: {
        color: 'white',
        fontWeight: 'bold',
        textAlign: 'center',
    },
    modalText: {
        marginBottom: 15,
        textAlign: 'center',
        fontSize: 18,
        fontWeight: 'bold',
    },
});

export default SocialSharing;

Resources.

Here are all the resources that have been used in this article. There is also a Github Repo where you can always go and tweak the sharing options. There are so many of them that i have not included here which include facebook sharing and Firebase analytics

Github Repo

https://github.com/cliffgor/RN_Learning

Image
Cliff Gor

About Cliff Gor

As a Fullstack Software Engineer, I design and develop user-centric and robust systems and applications using HTML, CSS, Bootstrap, React Js, React Native, and Kotlin(Android).

More articles like this

View all articles

Continue exploring React Native articles