Remember when adding social sharing buttons meant littering your website with a dozen third-party scripts, each one slowing down your page load? Or when "share this" functionality meant copying a URL to your clipboard and hoping for the best? The Web Share API changes all that, offering a native, performant way to tap into your device's sharing capabilities. Let's build a modern sharing system in React that your users will actually want to use.
Setting Up the Project
First, let's create a new React project using Vite. We'll use TypeScript for better developer experience and type safety:
npm create vite@latest my-share-app -- --template react-ts
cd my-share-app
Install the necessary dependencies:
npm install sonner
If you're using Tailwind CSS (optional but recommended for styling):
npm install -D tailwindcss@3 postcss autoprefixer
npx tailwindcss init -p
Add the toast provider to your main App component:
// src/App.tsx
import { Toaster } from 'sonner';
function App() {
return (
<>
<Toaster position="bottom-right" />
{/* Your app content */}
</>
);
}
Understanding the Web Share API
The Web Share API provides a platform-native sharing mechanism that integrates with the device's built-in sharing capabilities. On mobile devices, this means accessing the same sharing menu you use in native apps. On desktop, it typically interfaces with installed applications and system sharing features.
Creating the Share Hook
Let's build a custom hook that encapsulates our sharing logic. Create a new file src/hooks/useShare.ts
:
import { toast } from "sonner";
const useShare = () => {
const copy = async (text: string) => {
try {
await navigator.clipboard.writeText(text);
toast.success(`Successfully copied ${text} to clipboard`);
} catch (error) {
console.error("Error copying to clipboard:", error);
toast.error("Error copying to clipboard");
}
};
const share = async (url: string, title: string, description: string) => {
if (navigator.share) {
try {
await navigator.share({
title,
text: description,
url,
});
console.log("Successfully shared");
} catch (error) {
console.error("Error sharing:", error);
toast.error("Error sharing");
copy(url);
}
} else {
console.error("Web Share API not supported");
toast.error("Web Share API not supported");
copy(url);
}
};
return { copy, share };
};
export default useShare;
Breaking Down the Implementation
Our useShare
hook provides two main functions:
-
copy
: A fallback function that copies text to the clipboard using the Clipboard API -
share
: The primary sharing function that attempts to use the Web Share API first
The sharing logic follows a progressive enhancement approach:
- Check if the Web Share API is available (
navigator.share
) - If available, attempt to share using the native sharing mechanism
- If sharing fails or isn't supported, fall back to copying the URL to the clipboard
Using the Hook in Components
Here's a practical example of implementing a share button component:
// src/components/ShareButton.tsx
import { FC } from 'react';
import useShare from '../hooks/useShare';
interface ShareButtonProps {
url: string;
title: string;
description: string;
}
const ShareButton: FC<ShareButtonProps> = ({ url, title, description }) => {
const { share } = useShare();
const handleShare = () => {
share(url, title, description);
};
return (
<button
onClick={handleShare}
className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
>
Share This Content
</button>
);
};
export default ShareButton;
And here's how to use it in a page or component:
// src/App.tsx
import ShareButton from './components/ShareButton';
function App() {
return (
<div className="p-4">
<h1 className="text-2xl font-bold mb-4">My Awesome Content</h1>
<ShareButton
url={window.location.href}
title="Check out this awesome content!"
description="I found this really interesting article about the Web Share API..."
/>
</div>
);
}
Browser Support and Considerations
The Web Share API is well-supported on:
- Mobile browsers (iOS Safari, Chrome for Android)
- Desktop browsers (Chrome, Edge, Safari)
However, there are some important considerations:
- The API must be called from a secure context (HTTPS)
- It requires user interaction (like a button click)
- Not all browsers support sharing all types of data
Best Practices
Always provide fallbacks: As demonstrated in our implementation, always have a backup plan when the Web Share API isn't available.
Handle errors gracefully: Use toast notifications or other user feedback mechanisms to keep users informed about the sharing status.
Keep it simple: The sharing interface should be straightforward and intuitive. A simple button with clear messaging is often sufficient.
Test across devices: The sharing experience can vary significantly between desktop and mobile devices, so thorough testing is essential.
Resources
- Example Project on GitHub - https://github.com/miracleonyenma/my-share-app
Conclusion
The Web Share API provides a clean, native way to implement sharing functionality without bloating your app with third-party scripts. Combined with React hooks and proper fallback mechanisms, we can create a sharing system that feels natural and works reliably across platforms. The solution we've built is lightweight, maintainable, and most importantly, provides a sharing experience that feels native to each user's device.
For your next project, ditch those clunky social sharing libraries and give the Web Share API a try. Your users (and your bundle size) will thank you.
Top comments (0)