react-native-share

repository·main·Indexed 26 days ago

https://github.com/react-native-share/react-native-share

A tool for sharing messages and files with other applications in React Native projects. It provides functionality to trigger native system share sheets via Share.open(), target specific social platforms using shareSingle(), and verify Android package installations. The library includes UI components like Button, Sheet, and ShareSheet, and offers an Expo config plugin for managing Android manifest queries and iOS LSApplicationQueriesSchemes.

Tokens
11.7K
Snippets
36
Records
59
Agent score
86%

What's inside react-native-share

  1. Share a base64 file

    main

    To share a file using a base64 string, use the following URI format for the url parameter:

    data:<data_type>/<file_extension>;base64,<base64_data>

    Android Configuration (API 30+)

    For apps targeting Android API 30 (Android 11) or higher, you must set useInternalStorage: true when sharing base64 files. This is the recommended approach for all modern Android apps.

    Legacy Android (API 29 and below)

    If targeting API 29 or lower, you may need to add android.permission.WRITE_EXTERNAL_STORAGE to your AndroidManifest.xml, though this is deprecated and does not work on API 30+.

    // Recommended for Android API 30+
    Share.open({
      url: 'data:image/png;base64,<base64_data>',
      useInternalStorage: true,
    });
  2. Handle removal of WRITE_EXTERNAL_STORAGE permission request on Android

    main

    Starting with v4, react-native-share no longer requests the WRITE_EXTERNAL_STORAGE permission for apps targeting Android versions from KITKAT (API 19) and above. This is because the new storage location (getExternalCacheDir) is always accessible to the calling application without requiring explicit permissions.

    If your app's user flow or messaging expects a storage permission prompt to appear, you should update your application logic to account for its absence.

  3. Share images to Instagram (iOS Setup)

    main

    To share images to Instagram on iOS, you must request photo library permissions.

    1. Add permissions to Info.plist:

    <key>NSPhotoLibraryUsageDescription</key>
    <string>This app requires access to the photo library to save and share images on Instagram.</string>
    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>This app requires access to the photo library to save and share images on Instagram.</string>

    2. If using Expo, add to app.json / app.config.ts:

    expo: {
        ios: {
            infoPlist: {
                NSPhotoLibraryUsageDescription: 'This app requires access to the photo library to save and share images on Instagram',
                NSPhotoLibraryAddUsageDescription: 'This app requires access to the photo library to save and share images on Instagram.',
            },
        }
    }

    Usage:

    import Share, { Social } from 'react-native-share'
    
    await Share.shareSingle({
          social: Share.Social.INSTAGRAM,
          url: 'data:image/png;base64,<imageInBase64>',
          type: 'image/*'
        });
    import Share, { Social } from 'react-native-share'
    
    await Share.shareSingle({
          social: Share.Social.INSTAGRAM,
          url: 'data:image/png;base64,<imageInBase64>',
          type: 'image/*'
        });
  4. Share to Instagram Stories

    main

    To share content to Instagram Stories using Share.Social.INSTAGRAM_STORIES, you must provide a appId (Facebook App ID), which has been required since January 2023.

    Supported options for INSTAGRAM_STORIES:

    • appId (string, required): Facebook app ID.
    • backgroundImage (string): URL of the background image.
    • stickerImage (string): URL or base64 data of the sticker image.
    • backgroundBottomColor (string): Bottom color (default #837DF4).
    • backgroundTopColor (string): Top color (default #906df4).
    • attributionURL (string): Facebook beta-test URL.
    • backgroundVideo (string): URL of the video.
    • linkUrl (string): URL to be used as a link in the shared content.
    • linkText (string): Text to be used as a link in the shared content.
    import Share from 'react-native-share';
    
    const shareOptions = {
        backgroundImage: 'http://urlto.png',
        stickerImage: 'data:image/png;base64,<imageInBase64>', //or you can use "data:" link
        backgroundBottomColor: '#fefefe',
        backgroundTopColor: '#906df4',
        attributionURL: 'http://deep-link-to-app',
        social: Share.Social.INSTAGRAM_STORIES,
        appId: 'your_fb_app_id' // required since Jan 2023
    };
    
    Share.shareSingle(shareOptions);Fragile
  5. Share remote PDF files on Android using base64

    main

    On Android, you can share remote PDF files by downloading them via RNFetchBlob, converting the content to a base64 string, and passing that string to Share.open.

    Steps:

    1. Fetch the file using RNFetchBlob with fileCache: true.
    2. Convert the response to base64.
    3. Prepend the data URI scheme: data:${type};base64,.
    4. Call Share.open with the base64 URL.
    5. Clean up the cached file using RNFS.unlink.
    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);
        });
    }
  6. Manual Android Installation

    main

    To manually install on Android:

    1. In android/app/src/main/java/[...]/MainApplication.java, import cl.json.RNSharePackage and cl.json.ShareApplication. Add new RNSharePackage() to the getPackages() method.
    2. In android/settings.gradle, add:
      include ':react-native-share'
      project(':react-native-share').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-share/android')
    3. In android/app/build.gradle, add implementation project(':react-native-share') to the dependencies block.
  7. Share remote PDF files on iOS using a download workaround

    main

    On iOS, sharing PDF files via base64 can fail in apps like WhatsApp or result in incorrect file extensions (e.g., .dat) in Gmail. To resolve this, download the remote file to the device's temporary storage first and share the local file path instead of the base64 string.

    Requirements:

    1. Install react-native-fetch-blob.
    2. Configure RNFetchBlob with a specific path including the correct extension.
    3. Use RNFS.unlink to clean up the downloaded file after sharing.
    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);
        });
    }
  8. Migrate from v4 to v5 on Android: Handle WRITE_EXTERNAL_STORAGE removal

    main

    In version 5, react-native-share no longer automatically adds the WRITE_EXTERNAL_STORAGE permission to your app's AndroidManifest.xml. This change was made to comply with Android 11+ scoped storage restrictions.

    If you are using base64 file sharing, you must manually add the WRITE_EXTERNAL_STORAGE permission to your android/app/src/main/AndroidManifest.xml file.

    <!-- required for react-native-share base64 sharing -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  9. Run the Example App

    main

    To run the example application located in the ./example directory, follow these steps from the project root:

    1. Install dependencies and setup iOS pods:
      yarn && cd example/ios && pod install && cd -
    2. Start the Metro bundler:
      yarn start
    3. Launch the application:
      • iOS: Open example/ios/example.xcworkspace with Xcode.
      • Android: Run yarn start:android to start the Android simulator.
    yarn && cd example/ios && pod install && cd -
  10. Configure Android Queries for Package Visibility (SDK >= 30)

    main

    Android 11 (API level 30) and higher requires explicit <queries> declarations in AndroidManifest.xml to allow your app to see other installed packages. This is necessary for methods like Share.shareSingle() to work. You must provide the package name of the application you intend to share content through.

    <manifest package="com.example.game">
        <queries>
            <package android:name="com.example.store" />
            <package android:name="com.example.services" />
    
            <!-- for example, to share via instagram -->
            <package android:name="com.instagram.android" />
        </queries>
        ...
    </manifest>