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.github.io/react-native/table-of-contents
Installing
Install react native share package.
- for npm users
npm install react-native-share --save
- for yarn users
yarn add react-native-share
*** Install dependencies ( only for iOS )***
- install pod
cd ios && pod install
*** If you want share base64 image on your application ***
- add line on your
AndroidManifest.xml
<!-- required for react-native-share base64 sharing -->
<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.
npx 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
:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
<string>mailto</string>
<string>instagram</string>
<string>instagram-stories</string>
</array>
Also, to save photos your gallery you will need setting the following permission on your Info.plist
<key>NSPhotoLibraryAddUsageDescription</key>
<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
/**
* This functions share multiple images that
* you send as the urls param
*/
const shareMultipleImages = async () => {
const shareOptions = {
title: 'Share file',
failOnCancel: false,
urls: [images.image1, images.image2],
};
// If you want, you can use a try catch, to parse
// the share response. If the user cancels, etc.
try {
const ShareResponse = await Share.open(shareOptions);
setResult(JSON.stringify(ShareResponse, null, 2));
} catch (error) {
console.log('Error =>', error);
setResult('error: '.concat(getErrorString(error)));
}
};
share Email Image
/**
* This functions share a image passed using the
* url param
*/
const shareEmailImage = async () => {
const shareOptions = {
title: 'Share file',
email: 'email@example.com',
social: Share.Social.EMAIL,
failOnCancel: false,
urls: [images.image1, images.image2],
};
try {
const ShareResponse = await Share.open(shareOptions);
setResult(JSON.stringify(ShareResponse, null, 2));
} catch (error) {
console.log('Error =>', error);
setResult('error: '.concat(getErrorString(error)));
}
};
share single image
/**
* This functions share a image passed using the
* url param
*/
const shareSingleImage = async () => {
const shareOptions = {
title: 'Share file',
url: images.image1,
failOnCancel: false,
};
try {
const ShareResponse = await Share.open(shareOptions);
setResult(JSON.stringify(ShareResponse, null, 2));
} catch (error) {
console.log('Error =>', error);
setResult('error: '.concat(getErrorString(error)));
}
};
Share files
/**
* This function shares PDF and PNG files to
* the Files app that you send as the urls param
*/
const shareToFiles = async () => {
const shareOptions = {
title: 'Share file',
failOnCancel: false,
saveToFiles: true,
urls: [images.image1, images.pdf1], // base64 with mimeType or path to local file
};
// If you want, you can use a try catch, to parse
// the share response. If the user cancels, etc.
try {
const ShareResponse = await Share.open(shareOptions);
setResult(JSON.stringify(ShareResponse, null, 2));
} catch (error) {
console.log('Error =>', error);
setResult('error: '.concat(getErrorString(error)));
}
};
share Instagram Story
const shareToInstagramStory = async () => {
const shareOptions = {
title: 'Share image to instastory',
method: Share.InstagramStories.SHARE_BACKGROUND_IMAGE,
backgroundImage: images.image1,
social: Share.Social.INSTAGRAM_STORIES,
};
try {
const ShareResponse = await Share.shareSingle(shareOptions);
setResult(JSON.stringify(ShareResponse, null, 2));
} catch (error) {
console.log('Error =>', error);
setResult('error: '.concat(getErrorString(error)));
}
};
share to sms
const shareSms = async () => {
const shareOptions = {
title: '',
social: Share.Social.SMS,
recipient,
message: 'Example SMS',
};
try {
const ShareResponse = await Share.shareSingle(shareOptions);
setResult(JSON.stringify(ShareResponse, null, 2));
} catch (error) {
console.log('Error =>', error);
setResult('error: '.concat(getErrorString(error)));
}
};
share pdf base64
const sharePdfBase64 = async () => {
const shareOptions = {
title: '',
url: pdfBase64,
};
try {
const ShareResponse = await Share.open(shareOptions);
setResult(JSON.stringify(ShareResponse, null, 2));
} catch (error) {
console.log('sharePdfBase64 Error =>', error);
setResult('error: '.concat(getErrorString(error)));
}
};
react native share example
Complete code example of react native share
App.js
import React, {useState} from 'react';
import {
Alert,
Button,
Platform,
TextInput,
StyleSheet,
Text,
View,
} from 'react-native';
import Share from 'react-native-share';
import images from './images/imagesBase64';
import pdfBase64 from './images/pdfBase64';
const App = () => {
const [packageSearch, setPackageSearch] = useState('');
const [recipient, setRecipient] = useState('');
const [result, setResult] = useState('');
/**
* You can use the method isPackageInstalled to find if a package is installed.
* It returns an object { isInstalled, message }.
* Only works on Android.
*/
const checkIfPackageIsInstalled = async () => {
const {isInstalled} = await Share.isPackageInstalled(packageSearch);
Alert.alert(
`Package: ${packageSearch}`,
`${isInstalled ? 'Installed' : 'Not Installed'}`,
);
};
function getErrorString(error, defaultValue) {
let e = defaultValue || 'Something went wrong. Please try again';
if (typeof error === 'string') {
e = error;
} else if (error && error.message) {
e = error.message;
} else if (error && error.props) {
e = error.props;
}
return e;
}
/**
* This functions share multiple images that
* you send as the urls param
*/
const shareMultipleImages = async () => {
const shareOptions = {
title: 'Share file',
failOnCancel: false,
urls: [images.image1, images.image2],
};
// If you want, you can use a try catch, to parse
// the share response. If the user cancels, etc.
try {
const ShareResponse = await Share.open(shareOptions);
setResult(JSON.stringify(ShareResponse, null, 2));
} catch (error) {
console.log('Error =>', error);
setResult('error: '.concat(getErrorString(error)));
}
};
/**
* This functions share a image passed using the
* url param
*/
const shareEmailImage = async () => {
const shareOptions = {
title: 'Share file',
email: 'email@example.com',
social: Share.Social.EMAIL,
failOnCancel: false,
urls: [images.image1, images.image2],
};
try {
const ShareResponse = await Share.open(shareOptions);
setResult(JSON.stringify(ShareResponse, null, 2));
} catch (error) {
console.log('Error =>', error);
setResult('error: '.concat(getErrorString(error)));
}
};
/**
* This functions share a image passed using the
* url param
*/
const shareSingleImage = async () => {
const shareOptions = {
title: 'Share file',
url: images.image1,
failOnCancel: false,
};
try {
const ShareResponse = await Share.open(shareOptions);
setResult(JSON.stringify(ShareResponse, null, 2));
} catch (error) {
console.log('Error =>', error);
setResult('error: '.concat(getErrorString(error)));
}
};
/**
* This function shares PDF and PNG files to
* the Files app that you send as the urls param
*/
const shareToFiles = async () => {
const shareOptions = {
title: 'Share file',
failOnCancel: false,
saveToFiles: true,
urls: [images.image1, images.pdf1], // base64 with mimeType or path to local file
};
// If you want, you can use a try catch, to parse
// the share response. If the user cancels, etc.
try {
const ShareResponse = await Share.open(shareOptions);
setResult(JSON.stringify(ShareResponse, null, 2));
} catch (error) {
console.log('Error =>', error);
setResult('error: '.concat(getErrorString(error)));
}
};
const shareToInstagramStory = async () => {
const shareOptions = {
title: 'Share image to instastory',
method: Share.InstagramStories.SHARE_BACKGROUND_IMAGE,
backgroundImage: images.image1,
social: Share.Social.INSTAGRAM_STORIES,
};
try {
const ShareResponse = await Share.shareSingle(shareOptions);
setResult(JSON.stringify(ShareResponse, null, 2));
} catch (error) {
console.log('Error =>', error);
setResult('error: '.concat(getErrorString(error)));
}
};
const shareSms = async () => {
const shareOptions = {
title: '',
social: Share.Social.SMS,
recipient,
message: 'Example SMS',
};
try {
const ShareResponse = await Share.shareSingle(shareOptions);
setResult(JSON.stringify(ShareResponse, null, 2));
} catch (error) {
console.log('Error =>', error);
setResult('error: '.concat(getErrorString(error)));
}
};
const sharePdfBase64 = async () => {
const shareOptions = {
title: '',
url: pdfBase64,
};
try {
const ShareResponse = await Share.open(shareOptions);
setResult(JSON.stringify(ShareResponse, null, 2));
} catch (error) {
console.log('sharePdfBase64 Error =>', error);
setResult('error: '.concat(getErrorString(error)));
}
};
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to React Native Share Example!</Text>
<View style={styles.optionsRow}>
<View style={styles.button}>
<Button onPress={shareMultipleImages} title="Share Multiple Images" />
</View>
<View style={styles.button}>
<Button onPress={shareSingleImage} title="Share Single Image" />
</View>
<View style={styles.button}>
<Button onPress={shareEmailImage} title="Share Social: Email" />
</View>
<View style={styles.button}>
<Button onPress={shareToInstagramStory} title="Share to IG Story" />
</View>
<View style={styles.button}>
<Button onPress={shareToFiles} title="Share To Files" />
</View>
{Platform.OS === 'android' && (
<>
<View style={styles.button}>
<Button onPress={sharePdfBase64} title="Share Base64'd PDF url" />
</View>
<View style={styles.withInputContainer}>
<TextInput
placeholder="Recipient"
onChangeText={setRecipient}
value={recipient}
style={styles.textInput}
keyboardType="number-pad"
/>
<View>
<Button onPress={shareSms} title="Share Social: SMS" />
</View>
</View>
<View style={styles.withInputContainer}>
<TextInput
placeholder="Search for a Package"
onChangeText={setPackageSearch}
value={packageSearch}
style={styles.textInput}
/>
<View>
<Button
onPress={checkIfPackageIsInstalled}
title="Check Package"
/>
</View>
</View>
</>
)}
<Text style={styles.resultTitle}>Result</Text>
<Text style={styles.result}>{result}</Text>
</View>
</View>
);
};
const styles = StyleSheet.create({
button: {
marginBottom: 10,
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
textInput: {
borderBottomColor: '#151313',
borderBottomWidth: 1,
marginRight: 10,
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
resultTitle: {
marginTop: 20,
fontSize: 20,
},
result: {
fontSize: 14,
margin: 10,
},
optionsRow: {
justifyContent: 'space-between',
},
withInputContainer: {
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'row',
},
});
export 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
const [packageSearch, setPackageSearch] = useState<string>('');
const [recipient, setRecipient] = useState<string>('');
const [result, setResult] = useState<string>('');
To
const [packageSearch, setPackageSearch] = useState('');
const [recipient, setRecipient] = useState('');
const [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
Advances
4. React Native DatepickerAndroid
5. React native ScrollView scroll to position
6. How to align icon with text in react native
8. React Native Firebase Crashlytics
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
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