How to Share Image in React Native
Sharing images is one of the most commonly seen features in many mobile apps. In this blog post, let’s learn how to share an image from react native app using react native share library.
React Native Share is a popular third-party library for sharing content in React Native apps. It provides a simple API for sharing text, URLs, images, and other content with other apps installed on the device, and it supports Android and iOS platforms.
You can install the library using the following command.
npm i react-native-share --save
In the following example, we need one more library named react native blob util. It is used to convert the image to base64 data. After that, we share base64 data using react native share.
Following is the complete code where we share an image from a remote URL.
import {StyleSheet, Button, View} from 'react-native';
import React from 'react';
import ReactNativeBlobUtil from 'react-native-blob-util';
import Share from 'react-native-share';
function App() {
const shareImage = () => {
ReactNativeBlobUtil.fetch(
'GET',
'https://cdn.pixabay.com/photo/2021/12/29/08/18/insect-6900940_1280.jpg',
)
.then(res => {
let status = res.info().status;
if (status === 200) {
let base64Str = res.base64();
let options = {
url: `data:image/jpeg;base64,${base64Str}`,
};
Share.open(options)
.then(r => {
console.log(r);
})
.catch(e => {
e && console.log(e);
});
} else {
// handle other status codes
}
})
// Something went wrong:
.catch(err => {
// error handling
console.log(err);
});
};
return (
<View style={styles.container}>
<Button title="Click to Share Image" onPress={() => shareImage()} />
</View>
);
}
export default App;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
The shareImage function makes an HTTP GET request to retrieve an image from a URL using the ReactNativeBlobUtil library. If the image is successfully retrieved, the function converts it to a base64-encoded string and stores it in the base64Str variable.
It creates an options object that specifies the URL of the image encoded in base64 format. The Share.open method is then called with the options object as an argument, which opens the device’s sharing menu and allows the user to share the image with other apps.
Following is the output.
That’s how you share image with other apps in react native. I hope this tutorial is helpful for you.