Hello Friends,
Welcome To Infinitbility!
In this tutorial, we create react native app with share funtionallity of image, file, and text using react native share example.
This Article Part of React Native Tutorial Series want to start from scrach follow below link
https://infinitbility.com/react-native/table-of-contents
Installing
Install react native share package.
- for npm users
1npm install react-native-share --save
- for yarn users
1yarn add react-native-share
Install dependencies ( only for iOS )
- install pod
1cd ios && pod install
If you want share base64 image on your application
- add line on your
AndroidManifest.xml
1<!-- required for react-native-share base64 sharing -->2<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
sometime auto link not work for any reason, you can still run below command to link lib.
1npx react-native link react-native-share
LSApplicationQueriesSchemes (iOS only)
If you want to share Whatsapp, Mailto or some applications on iOS, you should write LSApplicationQueriesSchemes
in info.plist
:
1<key>LSApplicationQueriesSchemes</key>2 <array>3 <string>whatsapp</string>4 <string>mailto</string>5 <string>instagram</string>6 <string>instagram-stories</string>7 </array>
Also, to save photos your gallery you will need setting the following permission on your Info.plist
1<key>NSPhotoLibraryAddUsageDescription</key>2 <string>$(PRODUCT_NAME) wants to save photos</string>
( Now we are not adding Manual Install, if you facing any issue or want a tutorial to add your comment below )
sharing snipest from reat native share.
share multiple images
1/**2* This functions share multiple images that3* you send as the urls param4*/5const shareMultipleImages = async () => {6const shareOptions = {7 title: 'Share file',8 failOnCancel: false,9 urls: [images.image1, images.image2],10};1112// If you want, you can use a try catch, to parse13// the share response. If the user cancels, etc.14try {15 const ShareResponse = await Share.open(shareOptions);16 setResult(JSON.stringify(ShareResponse, null, 2));17} catch (error) {18 console.log('Error =>', error);19 setResult('error: '.concat(getErrorString(error)));20}21};
share Email Image
1/**2 * This functions share a image passed using the3 * url param4 */5 const shareEmailImage = async () => {6 const shareOptions = {7 title: 'Share file',9 social: Share.Social.EMAIL,10 failOnCancel: false,11 urls: [images.image1, images.image2],12 };1314 try {15 const ShareResponse = await Share.open(shareOptions);16 setResult(JSON.stringify(ShareResponse, null, 2));17 } catch (error) {18 console.log('Error =>', error);19 setResult('error: '.concat(getErrorString(error)));20 }21 };
share single image
1/**2 * This functions share a image passed using the3 * url param4 */5 const shareSingleImage = async () => {6 const shareOptions = {7 title: 'Share file',8 url: images.image1,9 failOnCancel: false,10 };1112 try {13 const ShareResponse = await Share.open(shareOptions);14 setResult(JSON.stringify(ShareResponse, null, 2));15 } catch (error) {16 console.log('Error =>', error);17 setResult('error: '.concat(getErrorString(error)));18 }19 };
Share files
1/**2 * This function shares PDF and PNG files to3 * the Files app that you send as the urls param4 */5 const shareToFiles = async () => {6 const shareOptions = {7 title: 'Share file',8 failOnCancel: false,9 saveToFiles: true,10 urls: [images.image1, images.pdf1], // base64 with mimeType or path to local file11 };1213 // If you want, you can use a try catch, to parse14 // the share response. If the user cancels, etc.15 try {16 const ShareResponse = await Share.open(shareOptions);17 setResult(JSON.stringify(ShareResponse, null, 2));18 } catch (error) {19 console.log('Error =>', error);20 setResult('error: '.concat(getErrorString(error)));21 }22 };
share Instagram Story
1const shareToInstagramStory = async () => {2 const shareOptions = {3 title: 'Share image to instastory',4 method: Share.InstagramStories.SHARE_BACKGROUND_IMAGE,5 backgroundImage: images.image1,6 social: Share.Social.INSTAGRAM_STORIES,7 };89 try {10 const ShareResponse = await Share.shareSingle(shareOptions);11 setResult(JSON.stringify(ShareResponse, null, 2));12 } catch (error) {13 console.log('Error =>', error);14 setResult('error: '.concat(getErrorString(error)));15 }16 };
share to sms
1const shareSms = async () => {2 const shareOptions = {3 title: '',4 social: Share.Social.SMS,5 recipient,6 message: 'Example SMS',7 };89 try {10 const ShareResponse = await Share.shareSingle(shareOptions);11 setResult(JSON.stringify(ShareResponse, null, 2));12 } catch (error) {13 console.log('Error =>', error);14 setResult('error: '.concat(getErrorString(error)));15 }16 };
share pdf base64
1const sharePdfBase64 = async () => {2const shareOptions = {3 title: '',4 url: pdfBase64,5};67try {8 const ShareResponse = await Share.open(shareOptions);9 setResult(JSON.stringify(ShareResponse, null, 2));10} catch (error) {11 console.log('sharePdfBase64 Error =>', error);12 setResult('error: '.concat(getErrorString(error)));13}14};
react native share example
Complete code example of react native share
App.js
1import React, {useState} from 'react';2import {3 Alert,4 Button,5 Platform,6 TextInput,7 StyleSheet,8 Text,9 View,10} from 'react-native';1112import Share from 'react-native-share';1314import images from './images/imagesBase64';15import pdfBase64 from './images/pdfBase64';1617const App = () => {18 const [packageSearch, setPackageSearch] = useState('');19 const [recipient, setRecipient] = useState('');20 const [result, setResult] = useState('');2122 /**23 * You can use the method isPackageInstalled to find if a package is installed.24 * It returns an object { isInstalled, message }.25 * Only works on Android.26 */27 const checkIfPackageIsInstalled = async () => {28 const {isInstalled} = await Share.isPackageInstalled(packageSearch);2930 Alert.alert(31 `Package: ${packageSearch}`,32 `${isInstalled ? 'Installed' : 'Not Installed'}`,33 );34 };3536 function getErrorString(error, defaultValue) {37 let e = defaultValue || 'Something went wrong. Please try again';38 if (typeof error === 'string') {39 e = error;40 } else if (error && error.message) {41 e = error.message;42 } else if (error && error.props) {43 e = error.props;44 }45 return e;46 }4748 /**49 * This functions share multiple images that50 * you send as the urls param51 */52 const shareMultipleImages = async () => {53 const shareOptions = {54 title: 'Share file',55 failOnCancel: false,56 urls: [images.image1, images.image2],57 };5859 // If you want, you can use a try catch, to parse60 // the share response. If the user cancels, etc.61 try {62 const ShareResponse = await Share.open(shareOptions);63 setResult(JSON.stringify(ShareResponse, null, 2));64 } catch (error) {65 console.log('Error =>', error);66 setResult('error: '.concat(getErrorString(error)));67 }68 };6970 /**71 * This functions share a image passed using the72 * url param73 */74 const shareEmailImage = async () => {75 const shareOptions = {76 title: 'Share file',78 social: Share.Social.EMAIL,79 failOnCancel: false,80 urls: [images.image1, images.image2],81 };8283 try {84 const ShareResponse = await Share.open(shareOptions);85 setResult(JSON.stringify(ShareResponse, null, 2));86 } catch (error) {87 console.log('Error =>', error);88 setResult('error: '.concat(getErrorString(error)));89 }90 };9192 /**93 * This functions share a image passed using the94 * url param95 */96 const shareSingleImage = async () => {97 const shareOptions = {98 title: 'Share file',99 url: images.image1,100 failOnCancel: false,101 };102103 try {104 const ShareResponse = await Share.open(shareOptions);105 setResult(JSON.stringify(ShareResponse, null, 2));106 } catch (error) {107 console.log('Error =>', error);108 setResult('error: '.concat(getErrorString(error)));109 }110 };111112 /**113 * This function shares PDF and PNG files to114 * the Files app that you send as the urls param115 */116 const shareToFiles = async () => {117 const shareOptions = {118 title: 'Share file',119 failOnCancel: false,120 saveToFiles: true,121 urls: [images.image1, images.pdf1], // base64 with mimeType or path to local file122 };123124 // If you want, you can use a try catch, to parse125 // the share response. If the user cancels, etc.126 try {127 const ShareResponse = await Share.open(shareOptions);128 setResult(JSON.stringify(ShareResponse, null, 2));129 } catch (error) {130 console.log('Error =>', error);131 setResult('error: '.concat(getErrorString(error)));132 }133 };134135 const shareToInstagramStory = async () => {136 const shareOptions = {137 title: 'Share image to instastory',138 method: Share.InstagramStories.SHARE_BACKGROUND_IMAGE,139 backgroundImage: images.image1,140 social: Share.Social.INSTAGRAM_STORIES,141 };142143 try {144 const ShareResponse = await Share.shareSingle(shareOptions);145 setResult(JSON.stringify(ShareResponse, null, 2));146 } catch (error) {147 console.log('Error =>', error);148 setResult('error: '.concat(getErrorString(error)));149 }150 };151152 const shareSms = async () => {153 const shareOptions = {154 title: '',155 social: Share.Social.SMS,156 recipient,157 message: 'Example SMS',158 };159160 try {161 const ShareResponse = await Share.shareSingle(shareOptions);162 setResult(JSON.stringify(ShareResponse, null, 2));163 } catch (error) {164 console.log('Error =>', error);165 setResult('error: '.concat(getErrorString(error)));166 }167 };168169 const sharePdfBase64 = async () => {170 const shareOptions = {171 title: '',172 url: pdfBase64,173 };174175 try {176 const ShareResponse = await Share.open(shareOptions);177 setResult(JSON.stringify(ShareResponse, null, 2));178 } catch (error) {179 console.log('sharePdfBase64 Error =>', error);180 setResult('error: '.concat(getErrorString(error)));181 }182 };183184 return (185 <View style={styles.container}>186 <Text style={styles.welcome}>Welcome to React Native Share Example!</Text>187 <View style={styles.optionsRow}>188 <View style={styles.button}>189 <Button onPress={shareMultipleImages} title="Share Multiple Images" />190 </View>191 <View style={styles.button}>192 <Button onPress={shareSingleImage} title="Share Single Image" />193 </View>194 <View style={styles.button}>195 <Button onPress={shareEmailImage} title="Share Social: Email" />196 </View>197 <View style={styles.button}>198 <Button onPress={shareToInstagramStory} title="Share to IG Story" />199 </View>200 <View style={styles.button}>201 <Button onPress={shareToFiles} title="Share To Files" />202 </View>203 {Platform.OS === 'android' && (204 <>205 <View style={styles.button}>206 <Button onPress={sharePdfBase64} title="Share Base64'd PDF url" />207 </View>208 <View style={styles.withInputContainer}>209 <TextInput210 placeholder="Recipient"211 onChangeText={setRecipient}212 value={recipient}213 style={styles.textInput}214 keyboardType="number-pad"215 />216 <View>217 <Button onPress={shareSms} title="Share Social: SMS" />218 </View>219 </View>220 <View style={styles.withInputContainer}>221 <TextInput222 placeholder="Search for a Package"223 onChangeText={setPackageSearch}224 value={packageSearch}225 style={styles.textInput}226 />227 <View>228 <Button229 onPress={checkIfPackageIsInstalled}230 title="Check Package"231 />232 </View>233 </View>234 </>235 )}236 <Text style={styles.resultTitle}>Result</Text>237 <Text style={styles.result}>{result}</Text>238 </View>239 </View>240 );241};242243const styles = StyleSheet.create({244 button: {245 marginBottom: 10,246 },247 container: {248 flex: 1,249 justifyContent: 'center',250 alignItems: 'center',251 backgroundColor: '#F5FCFF',252 },253 textInput: {254 borderBottomColor: '#151313',255 borderBottomWidth: 1,256 marginRight: 10,257 },258 welcome: {259 fontSize: 20,260 textAlign: 'center',261 margin: 10,262 },263 resultTitle: {264 marginTop: 20,265 fontSize: 20,266 },267 result: {268 fontSize: 14,269 margin: 10,270 },271 optionsRow: {272 justifyContent: 'space-between',273 },274 withInputContainer: {275 alignItems: 'center',276 justifyContent: 'center',277 flexDirection: 'row',278 },279});280281export default App;
Issue & Solution
when you want to install react native share example & you got Error like below
- ReferenceError: Can’t find variable: string
search code on your app
1const [packageSearch, setPackageSearch] = useState<string>('');2const [recipient, setRecipient] = useState<string>('');3const [result, setResult] = useState<string>('');
To
1const [packageSearch, setPackageSearch] = useState('');2const [recipient, setRecipient] = useState('');3const [result, setResult] = useState('');
Thanks for reading…
More From React Native Tutorial
Basics
- Introduction To React Native
- React Native Environment Setup using expo
- React Native Environment Setup for windows
- React Native Environment setup on Mac OS
- React Native Environment setup on linux
- React Native Project Structure
- React Native State
- React Native Props
- React Native Styling
- React Native Flexbox
- React Native Text
- React Native Textinput
- React Native Commands
- React Native ScrollView
Advances
- React Native Dark Mode
- React Native Fonts
- React Native SQLite
- React Native DatepickerAndroid
- React native ScrollView scroll to position
- How to align icon with text in react native
- React Native Image
- React Native Firebase Crashlytics
- React Native Async Storage
- React Native Share
Error & Issue Solution
- Task :app:transformDexArchiveWithDexMergerForDebug FAILED In React Native
- Expiring Daemon because JVM heap space is exhausted In React Native
- Task :app:transformNativeLibsWithMergeJniLibsForDebug FAILED In React Native
- Unable to determine the current character, it is not a string, number, array, or object in react native
- App crashed immediately after install react native video or track player
- how to delete SQLite database in android react native
- React native material dropdown twice click issue
- How to get the current route in react-navigation?
- how to disable drawer on the drawer navigation screen?
- Image not showing in ios 14 react native
- React Native image picker launchimagelibrary on second time issue
- how to open any link from react native render Html
- Network request failed in react native fetch
- React Native upload video example
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.