React Native Sharing

Almost all apps have a sharing feature to share interesting links and so on. With React Native we can implement this in a very easy way without any dependency.

The complete Sharing API can be found here

The Sharing API is self explaining, you have some required fields and some OS specific fields.

A basic sharing function can could like this:

Share.share({
  title: "What the ...",
  message: "Some very cool news about ...",
});

On iOS you need to add an URL to share the Website you want.

Share.share({
  title: "What the ...",
  message: "Some very cool news about ...",
  url: "http://example.com",
});

This is a very basic approach to share content but we can improve this with some "controlling". React Native gives us two Functions to determine the status of a shared content.

static sharedAction()

The content was successfully shared.

static dismissedAction()

The dialog has been dismissed. (iOS only)

A complete example could look like this:

import React from 'react'
import { Share, Button } from 'react-native'
class ShareExample extends React.Component {
  onShare = async () => {
    try {
      const result = await Share.share({
        title: 'React Native Sharing'
        message: 'How we can share content with React Native.',
        url: 'https://hashdot.co/blog/react-native-sharing'
      })
      if (result.action === Share.sharedAction) {
        if (result.activityType) {
          // shared with activity type of result.activityType
        } else {
          // shared
        }
      } else if (result.action === Share.dismissedAction) {
        // dismissed
      }
    } catch (error) {
      alert(error.message)
    }
  }
  render() {
    return <Button onPress={this.onShare} title="Share" />
  }
}