useHooks.iov4.1.2
DocsBlogGitHub
Hooks
No hooks found in any category.

useWebShare

browser

Installation

npx usehooks-cli@latest add use-web-share

Description

A React hook for sharing content using the Web Share API. Provides native sharing capabilities with comprehensive error handling and support detection.

Return Type

UseWebShareReturn
PropertyTypeDescription
isLoadingbooleanWhether a share operation is currently in progress
errorstring | nullError message if sharing failed
isSupportedbooleanWhether the Web Share API is supported in the current browser
share(data: ShareData) => Promise<boolean>Function to share content, returns true if successful
canShare(data?: ShareData) => booleanFunction to check if specific data can be shared
clearError() => voidFunction to clear the current error state

Examples

Share article content

Basic sharing functionality with error handling

1import { useWebShare } from '@usehooks.io/use-web-share'; 2 3function ArticleShare() { 4 const { share, canShare, isLoading, error, isSupported, clearError } = useWebShare(); 5 6 const shareArticle = async () => { 7 const shareData = { 8 title: 'Amazing Article', 9 text: 'Check out this amazing article!', 10 url: window.location.href 11 }; 12 13 if (canShare(shareData)) { 14 const success = await share(shareData); 15 if (success) { 16 console.log('Article shared successfully!'); 17 } 18 } 19 }; 20 21 if (!isSupported) { 22 return <div>Web Share API not supported</div>; 23 } 24 25 return ( 26 <div> 27 <button onClick={shareArticle} disabled={isLoading}> 28 {isLoading ? 'Sharing...' : 'Share Article'} 29 </button> 30 31 {error && ( 32 <div style={{ color: 'red' }}> 33 Error: {error} 34 <button onClick={clearError}>Clear</button> 35 </div> 36 )} 37 </div> 38 ); 39}

Dependencies

react

Notes

  • Web Share API requires user activation (user gesture) to work
  • File sharing support varies by browser and platform
  • At least one of title, text, url, or files must be provided
  • Provides detailed error messages for different failure scenarios
  • Share targets depend on installed apps and browser capabilities

Implementation

1'use client'; 2 3import { useState, useCallback } from "react"; 4 5interface ShareData { 6 title?: string; 7 text?: string; 8 url?: string; 9 files?: File[]; 10} 11 12interface UseWebShareReturn { 13 isLoading: boolean; 14 error: string | null; 15 isSupported: boolean; 16 share: (data: ShareData) => Promise<boolean>; 17 canShare: (data?: ShareData) => boolean; 18 clearError: () => void; 19} 20 21export const useWebShare = (): UseWebShareReturn => { 22 const [isLoading, setIsLoading] = useState(false); 23 const [error, setError] = useState<string | null>(null); 24 25 // Check if Web Share API is supported 26 const isSupported = 27 typeof navigator !== "undefined" && 28 "share" in navigator && 29 typeof navigator.share === "function"; 30 31 // Check if data can be shared 32 const canShare = useCallback( 33 (data?: ShareData): boolean => { 34 if (!isSupported || !navigator.canShare) { 35 return false; 36 } 37 38 if (!data) { 39 return true; 40 } 41 42 try { 43 return navigator.canShare(data); 44 } catch { 45 return false; 46 } 47 }, 48 [isSupported] 49 ); 50 51 // Share data using the Web Share API 52 const share = useCallback( 53 async (data: ShareData): Promise<boolean> => { 54 if (!isSupported || !navigator.share) { 55 setError("Web Share API is not supported"); 56 return false; 57 } 58 59 // Validate that at least one known property is provided 60 if (!data.title && !data.text && !data.url && !data.files?.length) { 61 setError("At least one of title, text, url, or files must be provided"); 62 return false; 63 } 64 65 // Check if the data can be shared 66 if (navigator.canShare && !navigator.canShare(data)) { 67 setError("The provided data cannot be shared"); 68 return false; 69 } 70 71 try { 72 setIsLoading(true); 73 setError(null); 74 75 await navigator.share(data); 76 return true; 77 } catch (err) { 78 let errorMessage = "Failed to share"; 79 80 if (err instanceof Error) { 81 // Handle specific error cases 82 switch (err.name) { 83 case "InvalidStateError": 84 errorMessage = 85 "Document is not fully active or other sharing operations are in progress"; 86 break; 87 case "NotAllowedError": 88 errorMessage = 89 "Sharing is not allowed. This may be due to permissions policy, lack of user activation, or security restrictions"; 90 break; 91 case "TypeError": 92 errorMessage = 93 "The share data is invalid. Check that URLs are properly formatted and data is valid"; 94 break; 95 case "AbortError": 96 errorMessage = 97 "Share was cancelled by the user or no share targets are available"; 98 break; 99 case "DataError": 100 errorMessage = 101 "There was a problem starting the share target or transmitting the data"; 102 break; 103 default: 104 errorMessage = 105 err.message || "An unknown error occurred while sharing"; 106 } 107 } 108 109 setError(errorMessage); 110 return false; 111 } finally { 112 setIsLoading(false); 113 } 114 }, 115 [isSupported] 116 ); 117 118 // Clear error state 119 const clearError = useCallback(() => { 120 setError(null); 121 }, []); 122 123 return { 124 isLoading, 125 error, 126 isSupported, 127 share, 128 canShare, 129 clearError, 130 }; 131}; 132