Search code examples
androidreactjsweb-share

Sharing on React JS Mobile application


I am trying to get my application to allow sharing to other apps but I can't seem to figure it out.

I am using React JS and have tried to use the following code

        // Check if navigator.share is supported by the browser
        if (navigator.share) {
            console.log("Congrats! Your browser supports Web Share API");
            navigator
                .share({
                    url: "https://www.google.com",
                    text: "add text",
                    title: "Your Discovery",
                })
                .then(() => {
                    console.log("Sharing successfull");
                })
                .catch(() => {
                    console.log("Sharing failed");
                });
        } else {
            console.log("Sorry! Your browser does not support Web Share API");
        }
    };

I gathered this wouldn't work on my application as its not a supported browser type. But was wondering if it would work if I launched an in app browser through my application?

Or does anyone know how to add native sharing capabilities to a react js application.

Thank you.


Solution

  • This is how I solved the problem! My app is built using ionic and react js and this was the only solution that worked on native devices.

     import { Share } from '@capacitor/share';
        
        const [basicShare, setBasicShare] = useState(false)
        
        
        useEffect(() => () => {
                if (basicShare) {
                    Share.share({
                        title: 'Title',
                        text: 'enter text',
                        url: "https://google.com",
                        dialogTitle: 'Share',
                    });
                }
                setBasicShare(false)
        
            },
                [basicShare]);