React Native - Share Method Cancel Event

Viewed 2306

i am using React Native Share Method (https://facebook.github.io/react-native/docs/share.html) to share content on Android.

As per documentation, we can use it in following ways:

Share.share({
        message: 'React Native | A framework for building native apps using React'
    })
    .then((result) => {
        console.log(result.action) // returns sharedAction 
    })
    .catch((error) => {
        console.log(error)
    })

So when we call Share method, we will get result in then and popup window is appeared which contains apps list with which we can share the message content.

Issue:

Popup window also contains a cancel button, so when user click on it, window get closed, but there is no method available/mentioned to capture it, in docs.

Is there any way to capture the cancel event, as i want to perform some action when user clicks on it.

Thanks in adv. :)

2 Answers

There is option in share dismissedAction but unfortunately this is IOS only . You can use react-native-share with prop "failOnCancel" to true and it will work on both android and ios

Sample Code

import React, { Component } from "react";
import { Button } from "react-native";

import Share from "react-native-share";

export default class ShareExample extends Component {
  onShare = async () => {
    const shareOptions = {
      title: "Share file",
      social: Share.Social.EMAIL,
      failOnCancel: true
    };

    try {
      const ShareResponse = await Share.open(shareOptions);
      //setResult(JSON.stringify(ShareResponse, null, 2));
    } catch (error) {
      console.log("Error =>", error);
    }
  };

  render() {
    return <Button onPress={this.onShare} title="Share" />;
  }
}

App Preview

enter image description here

This might help

import React, {Component} from 'react';
import {Share, Button} from 'react-native';

class ShareExample extends Component {
  onShare = async () => {
    try {
      const result = await Share.share({
        message:
          'React Native | A framework for building native apps using React',
      });

      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" />;
  }
}
Related