Navigate back to the homepage

React Native Share

Infinitbility
React Native
January 30th, 2021 · 1 min read
React Native Share

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 that
3* you send as the urls param
4*/
5const shareMultipleImages = async () => {
6const shareOptions = {
7 title: 'Share file',
8 failOnCancel: false,
9 urls: [images.image1, images.image2],
10};
11
12// If you want, you can use a try catch, to parse
13// 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 the
3 * url param
4 */
5 const shareEmailImage = async () => {
6 const shareOptions = {
7 title: 'Share file',
8 email: '[email protected]',
9 social: Share.Social.EMAIL,
10 failOnCancel: false,
11 urls: [images.image1, images.image2],
12 };
13
14 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 the
3 * url param
4 */
5 const shareSingleImage = async () => {
6 const shareOptions = {
7 title: 'Share file',
8 url: images.image1,
9 failOnCancel: false,
10 };
11
12 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 to
3 * the Files app that you send as the urls param
4 */
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 file
11 };
12
13 // If you want, you can use a try catch, to parse
14 // 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 };
8
9 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 };
8
9 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};
6
7try {
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';
11
12import Share from 'react-native-share';
13
14import images from './images/imagesBase64';
15import pdfBase64 from './images/pdfBase64';
16
17const App = () => {
18 const [packageSearch, setPackageSearch] = useState('');
19 const [recipient, setRecipient] = useState('');
20 const [result, setResult] = useState('');
21
22 /**
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);
29
30 Alert.alert(
31 `Package: ${packageSearch}`,
32 `${isInstalled ? 'Installed' : 'Not Installed'}`,
33 );
34 };
35
36 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 }
47
48 /**
49 * This functions share multiple images that
50 * you send as the urls param
51 */
52 const shareMultipleImages = async () => {
53 const shareOptions = {
54 title: 'Share file',
55 failOnCancel: false,
56 urls: [images.image1, images.image2],
57 };
58
59 // If you want, you can use a try catch, to parse
60 // 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 };
69
70 /**
71 * This functions share a image passed using the
72 * url param
73 */
74 const shareEmailImage = async () => {
75 const shareOptions = {
76 title: 'Share file',
77 email: '[email protected]',
78 social: Share.Social.EMAIL,
79 failOnCancel: false,
80 urls: [images.image1, images.image2],
81 };
82
83 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 };
91
92 /**
93 * This functions share a image passed using the
94 * url param
95 */
96 const shareSingleImage = async () => {
97 const shareOptions = {
98 title: 'Share file',
99 url: images.image1,
100 failOnCancel: false,
101 };
102
103 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 };
111
112 /**
113 * This function shares PDF and PNG files to
114 * the Files app that you send as the urls param
115 */
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 file
122 };
123
124 // If you want, you can use a try catch, to parse
125 // 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 };
134
135 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 };
142
143 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 };
151
152 const shareSms = async () => {
153 const shareOptions = {
154 title: '',
155 social: Share.Social.SMS,
156 recipient,
157 message: 'Example SMS',
158 };
159
160 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 };
168
169 const sharePdfBase64 = async () => {
170 const shareOptions = {
171 title: '',
172 url: pdfBase64,
173 };
174
175 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 };
183
184 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 <TextInput
210 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 <TextInput
222 placeholder="Search for a Package"
223 onChangeText={setPackageSearch}
224 value={packageSearch}
225 style={styles.textInput}
226 />
227 <View>
228 <Button
229 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};
242
243const 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});
280
281export default App;

Issue & Solution

when you want to install react native share example & you got Error like below

  1. 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

  1. Introduction To React Native
  2. React Native Environment Setup using expo
  3. React Native Environment Setup for windows
  4. React Native Environment setup on Mac OS
  5. React Native Environment setup on linux
  6. React Native Project Structure
  7. React Native State
  8. React Native Props
  9. React Native Styling
  10. React Native Flexbox
  11. React Native Text
  12. React Native Textinput
  13. React Native Commands
  14. React Native ScrollView

Advances

  1. React Native Dark Mode
  2. React Native Fonts
  3. React Native SQLite
  4. React Native DatepickerAndroid
  5. React native ScrollView scroll to position
  6. How to align icon with text in react native
  7. React Native Image
  8. React Native Firebase Crashlytics
  9. React Native Async Storage
  10. React Native Share

Error & Issue Solution

  1. Task :app:transformDexArchiveWithDexMergerForDebug FAILED In React Native
  2. Expiring Daemon because JVM heap space is exhausted In React Native
  3. Task :app:transformNativeLibsWithMergeJniLibsForDebug FAILED In React Native
  4. Unable to determine the current character, it is not a string, number, array, or object in react native
  5. App crashed immediately after install react native video or track player
  6. how to delete SQLite database in android react native
  7. React native material dropdown twice click issue
  8. How to get the current route in react-navigation?
  9. how to disable drawer on the drawer navigation screen?
  10. Image not showing in ios 14 react native
  11. React Native image picker launchimagelibrary on second time issue
  12. how to open any link from react native render Html

Looking For React Native Tutorial?

we are trying to create the best Tutorial for react native developers.

When you want a daily updates about React Native Tutorial or infinitbility update subscribe to our newsletter.

Read React Native Tutorial

Request New Tutorial or Article on mail [email protected]

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.

More articles from Infinitbility

Image not showing in ios 14 react native

Image not showing in ios 14 react native

How to solve React Native show image issue in iOS 14

January 22nd, 2021 · 1 min read
Laravel Model

Laravel Model

Laravel model required things to done to your project to use laravel models.

January 20th, 2021 · 1 min read
© 2020–2021 Infinitbility
Disclaimer
Link to $https://medium.com/infinitbilityLink to $https://www.facebook.com/InfinitbilityLink to $https://github.com/infinitbilityLink to $https://twitter.com/infinitbilityLink to $https://www.buymeacoffee.com/infinitbilityLink to $mailto:[email protected]