Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
react-native-share
Advanced tools
The react-native-share package allows you to share content such as text, images, and files from your React Native app to other apps on the user's device. It supports both Android and iOS platforms.
Share Text
This feature allows you to share plain text messages. The code sample demonstrates how to share a simple text message using the react-native-share package.
import Share from 'react-native-share';
const shareText = async () => {
const shareOptions = {
message: 'Hello, this is a text message!',
};
try {
await Share.open(shareOptions);
} catch (error) {
console.log('Error =>', error);
}
};
Share Image
This feature allows you to share images. The code sample demonstrates how to share an image using a base64 encoded string.
import Share from 'react-native-share';
const shareImage = async () => {
const shareOptions = {
url: 'data:image/png;base64,<base64_encoded_image>',
};
try {
await Share.open(shareOptions);
} catch (error) {
console.log('Error =>', error);
}
};
Share File
This feature allows you to share files. The code sample demonstrates how to share a file from a given file path.
import Share from 'react-native-share';
const shareFile = async () => {
const shareOptions = {
url: 'file://path/to/your/file.pdf',
};
try {
await Share.open(shareOptions);
} catch (error) {
console.log('Error =>', error);
}
};
Share with Social Media
This feature allows you to share content directly to specific social media apps. The code sample demonstrates how to share a message directly to WhatsApp.
import Share from 'react-native-share';
const shareToWhatsApp = async () => {
const shareOptions = {
message: 'Hello, sharing this via WhatsApp!',
social: Share.Social.WHATSAPP,
};
try {
await Share.shareSingle(shareOptions);
} catch (error) {
console.log('Error =>', error);
}
};
The react-native-social-share package allows you to share content to social media platforms like Facebook, Twitter, and WhatsApp. It is more focused on social media sharing compared to react-native-share, which offers a broader range of sharing options.
The react-native-share-menu package allows your app to receive content shared from other apps. While react-native-share focuses on sharing content from your app, react-native-share-menu is designed to handle incoming shared content.
The expo-sharing package is part of the Expo ecosystem and allows you to share files with other apps. It is simpler to use within Expo-managed projects but may not offer as many customization options as react-native-share.
React Native Share, a simple tool for share message and file to other apps.
If you use this library on your commercial/personal projects, you can help us by funding the work on specific issues that you choose by using IssueHunt.io!
This gives you the power to prioritize our work and support the project contributors. Moreover it'll guarantee the project will be updated and maintained in the long run.
react-native
>= 0.60.0 please use react-native-share
>= 2.0.0yarn add react-native-share
or if you're using npm
npm install react-native-share --save
Linking is not needed anymore. react-native@0.60.0+
supports dependencies auto linking.
For iOS you also need additional step to install auto linked Pods (Cocoapods should be installed):
cd ios && pod install && cd ../
react-native
<= 0.59.10 please use react-native-share
<= 1.2.1:If you are having any problems with this library, or need to use >= 2.0.0 please refer to: jetifier.
After installing jetifier, runs a npx jetify -r
and test if this works by running a react-native run-android
.
yarn add react-native-share
react-native link react-native-share
or if you're using npm
npm install react-native-share --save
react-native link react-native-share
We recommend using the releases from npm, however you can use the master branch if you need any feature that is not available on NPM. By doing this you will be able to use unreleased features, but the module may be less stable. yarn:
yarn add react-native-share@git+https://git@github.com/react-native-community/react-native-share.git
yarn add react-native-share
Libraries
➜ Add Files to [your project's name]
node_modules
➜ react-native-share
➜ ios
and add RNShare.xcodeproj
libRNShare.a
to your project's Build Phases
➜ Link Binary With Libraries
Social.framework
and MessageUI.framework
to your project's General
➜ Linked Frameworks and Libraries
LSApplicationQueriesSchemes
in info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
<string>mailto</string>
</array>
info.plist
<key>NSPhotoLibraryAddUsageDescription</key>
<string>$(PRODUCT_NAME) wants to save photos</string>
Cmd+R
)If you wish, you can use cocopoads to use react-native-share.
You just need to add to your Podfile the react-native-share dependency.
# React-Native-Share pod
pod 'RNShare', :path => '../node_modules/react-native-share'
After that, just run a pod install
or pod udpate
to get up and running with react-native-share.
Then run a react-native link react-native-share
, and doing the steps 6 and 7.
You can also see our example to see how you need to setup your podfile.
Btw, We also recommend reading this (amazing article)[https://shift.infinite.red/beginner-s-guide-to-using-cocoapods-with-react-native-46cb4d372995] about how pods and rn work together. =D
yarn add react-native-share
Open up android/app/src/main/java/[...]/MainApplication.java
import cl.json.RNSharePackage;
and import cl.json.ShareApplication;
to the imports at the top of the filenew RNSharePackage()
to the list returned by the getPackages()
methodAppend the following lines to android/settings.gradle
:
include ':react-native-share'
project(':react-native-share').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-share/android')
Insert the following lines inside the dependencies block in
android/app/build.gradle
:
compile project(':react-native-share')
(Optional) Follow this for implementing Provider
yarn add react-native-share
RNShare.sln
in node_modules/react-native-share/windows/RNShare.sln
folder to their solution, reference from their app.MainPage.cs
appusing Cl.Json.RNShare;
to the usings at the top of the filenew RNSharePackage()
to the List<IReactPackage>
returned by the Packages
methodOpen Simple share dialog
Returns a promise that fulfills or rejects as soon as user successfully open the share action sheet or cancelled/failed to do so. As a result you might need to further handle the rejection while necessary. e.g.
*For share multiple files, you must using option urls instead of url to share multiple files/images/docs. Example could be found in Example folder
Share.open(options)
.then((res) => { console.log(res) })
.catch((err) => { err && console.log(err); });
Supported options:
Name | Type | Description |
---|---|---|
url | string | URL you want to share (only support base64 string in iOS & Android ). |
urls | Array[string] | array of base64 string you want to share (only support iOS & Android). |
type | string | File mime type (optional) |
message | string | |
title | string | (optional) |
subject | string | (optional) |
excludedActivityTypes | string | (optional) |
failOnCancel | boolean | (defaults to true) Specifies whether promise should reject if user cancels share dialog (optional) |
showAppsToView | boolean | (optional) only android |
***Share base 64 file
When share a base 64 file, please follow the format below:
url: "data:<data_type>/<file_extension>;base64,<base64_data>"
***Share file directly
When share a local file directly, please follow the format below:
url: "file://<file_path>",
Open share dialog with specific application
This returns a promise too.
Supported options:
Name | Type | Description |
---|---|---|
url | string | URL you want to share |
type | string | File mime type (optional) |
message | string | |
title | string | (optional) |
subject | string | (optional) |
social | string | supported social apps: List |
forceDialog | boolean | (optional) only android. Avoid showing dialog with buttons Just Once / Always. Useful for Instagram to always ask user if share as Story or Feed |
NOTE: If both message
and url
are provided, url
will be concatenated to the end of message
to form the body of the message. If only one is provided it will be used
It's a method that checks if an app (package) is installed on Android.
It returns a promise with isInstalled
. e.g.
Checking if Instagram is installed on Android.
Share.isPackageInstalled('com.instagram.android')
.then(({ isInstalled }) => console.log(isInstalled))
NOTE: in iOS you can use Linking.canOpenURL(url)
These can be assessed using Share.Social property For eg.
import Share from 'react-native-share';
const shareOptions = {
title: 'Share via',
message: 'some message',
url: 'some share url',
social: Share.Social.WHATSAPP
};
Share.shareSingle(shareOptions);
Name | Android | iOS | Windows |
---|---|---|---|
yes | yes | no | |
PAGESMANAGER | yes | no | no |
yes | yes | no | |
yes | yes | no | |
GOOGLEPLUS | yes | yes | no |
yes | yes | no | |
yes | no | no | |
SMS | yes | no | no |
SNAPCHAT | yes | no | no |
MESSENGER | yes | no | no |
yes | no | no |
Android | IOS | Windows | |
---|---|---|---|
Simple Share | |||
UI Component | TODO |
When sharing a pdf file with base64, there are two current problems.
Therefore we use this "workaround" in order to handle pdf sharing for iOS Apps to mentioned Apps
Code:
static sharePDFWithIOS(fileUrl, type) {
let filePath = null;
let file_url_length = fileUrl.length;
const configOptions = {
fileCache: true,
path:
DIRS.DocumentDir + (type === 'application/pdf' ? '/SomeFileName.pdf' : '/SomeFileName.png') // no difference when using jpeg / jpg / png /
};
RNFetchBlob.config(configOptions)
.fetch('GET', fileUrl)
.then(async resp => {
filePath = resp.path();
let options = {
type: type,
url: filePath // (Platform.OS === 'android' ? 'file://' + filePath)
};
await Share.open(options);
// remove the image or pdf from device's storage
await RNFS.unlink(filePath);
});
}
Nothing to do on Android. You can share the pdf file with base64
static sharePDFWithAndroid(fileUrl, type) {
let filePath = null;
let file_url_length = fileUrl.length;
const configOptions = { fileCache: true };
RNFetchBlob.config(configOptions)
.fetch('GET', fileUrl)
.then(resp => {
filePath = resp.path();
return resp.readFile('base64');
})
.then(async base64Data => {
base64Data = `data:${type};base64,` + base64Data;
await Share.open({ url: base64Data });
// remove the image or pdf from device's storage
await RNFS.unlink(filePath);
});
}
applicationId
should be defined in the defaultConfig
section in your android/app/build.gradle
:
File: android/app/build.gradle
defaultConfig {
applicationId "com.yourcompany.yourappname"
...
}
Add this <provider>
section to your AndroidManifest.xml
File: AndroidManifest.xml
<application>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
</application>
Create a filepaths.xml
under this directory:
android/app/src/main/res/xml
.
In this file, add the following contents:
File: android/app/src/main/res/filepaths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="myexternalimages" path="Download/" />
</paths>
Edit your MainApplication.java
class to add implements ShareApplication
and getFileProviderAuthority
The getFileProviderAuthority
function returns the android:authorities
value added in the AndroidManifest.xml
file
applicationId
is defined in the defaultConfig
section of your android/app/build.gradle
and referenced using BuildConfig.APPLICATION_ID
import cl.json.ShareApplication
public class MainApplication extends Application implements ShareApplication, ReactApplication {
@Override
public String getFileProviderAuthority() {
return BuildConfig.APPLICATION_ID + ".provider";
}
// ...Your own code
}
FAQs
Social share, sending simple data to other apps.
The npm package react-native-share receives a total of 252,570 weekly downloads. As such, react-native-share popularity was classified as popular.
We found that react-native-share demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 6 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.