Hi everyone, In this article we are going to learn about How to use react-native-share package which use to share data from App to social media. Now days, sharing content from mobile apps is a powerful way to engage users and extend the reach of your application. React Native, a popular cross-platform framework, makes it seamless to integrate such features. In this tutorial, we’ll explore how to use the react-native-share library to implement social sharing functionality in your React Native app.
1. Install library
Use following command to install react-native-share in your project.
npm i react-native-share --save
After successfully install, If you are run project on iOS then run Pod install command in you project iOS folder. this will install RNShare in your iOS project like below
2. Importing the Library
Import the Share module from react-native-share.
import Share from 'react-native-share';
3. Handling Share Action
Create a function handleShare that defines the sharing options (in this case, a title and a message) and uses Share.open to open the share dialog.
const handleShare = async () => { try { const shareOptions = { title: 'Share via', message: 'Check this blog to learn more about React Native issues', }; await Share.open(shareOptions); } catch (error) { console.error('++++Error sharing data:', error.message); } };
4. Creating the UI
return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <TouchableOpacity onPress={handleShare}> <Text>Share Now</Text> </TouchableOpacity> </View> );
5. Full source code
import React from 'react'; import { View, TouchableOpacity, Text } from 'react-native'; import Share from 'react-native-share'; const App = () => { // Function to handle the share action const handleShare = async () => { try { const shareOptions = { title: 'Share via', message: 'Check this blog to learn more about React Native issues', }; await Share.open(shareOptions); } catch (error) { console.error('+++++Error sharing data:', error.message); } }; return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <TouchableOpacity onPress={handleShare}> <Text>Share Now</Text> </TouchableOpacity> </View> ); }; export default App;