How to display native (default) android share tray in React JS

If you are a React.JS Developer, chances are you have tried your luck with react-share library and were unable to find a way to configure a way to display default android share tray in mobile view.

Worry not we have written the code for you, you can just use it in your project.

To open the default sharing tray of Android when a specific element, you can use the Web Share API.This API allows you to trigger the native sharing dialog provided by the user’s device. Here’s how you can do it in a React.js application:

import React from ‘react’;

function DefaultAndroidTrayComponent() {
const handleShare = async () => {
if (navigator.share) {
try {
await navigator.share({
title: ‘TItle’,
text: ‘Check out this!’,
url: ‘https://example.com/myUrl’, // Replace with the actual URL
});
console.log(‘Shared successfully’);
} catch (error) {
console.error(‘Error sharing:’, error);
}
} else {
console.error(‘Web Share API is not supported in this browser’);
}
};

return (

Certificate

{/* Add your content here */}

);
}

export default DefaultAndroidTrayComponent;

Ensure that your React application is running in a secure context (i.e., over HTTPS) because the Web Share API requires it.

Check if the Web Share API is available in the user’s browser before using it, as it may not be supported in all browsers. You can do this by checking if navigator.share is defined.

Attach an onClick event handler to the certificate element and call the navigator.share method to trigger the native sharing dialog when the element is clicked.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top