Content sharing is a fundamental feature that bridges your React Native application with the broader mobile ecosystem. Whether users want to share a product link, send a document, or distribute media files, implementing robust sharing functionality directly impacts user engagement and app utility.
The React Native Share library provides a unified API that abstracts platform-specific sharing mechanisms, enabling developers to implement social sharing features with minimal platform-specific code. Our web development services team regularly implements these patterns in production React Native applications. This guide explores the React Native Share library in depth, covering everything from basic text sharing to advanced file distribution and custom share extension integration.
Getting Started with React Native Share
What is React Native Share?
React Native Share is a community-maintained library that provides a simple interface for sharing content from your React Native application to other apps installed on the user's device. The library wraps the native sharing capabilities of iOS (UIActivityViewController) and Android (Intent system) into a consistent JavaScript API that works seamlessly across both platforms.
This abstraction allows developers to implement sharing functionality without writing platform-specific code, while still respecting the unique behaviors and limitations of each operating system. The library supports various content types including plain text, rich text with URLs, and files of different formats.
For detailed information about the library's capabilities, refer to the official React Native Share documentation.
Installation and Setup
Installing React Native Share requires adding the package to your project and performing platform-specific configuration. For projects using React Native 0.60 and above, the library supports automatic linking, though manual configuration may still be necessary for certain scenarios.
1npm install react-native-share --save1yarn add react-native-shareiOS Setup
After installing the package, iOS projects require running pod install to link the native dependencies:
1cd ios && pod install && cd ..Android Configuration
React Native Share works out of the box on Android without additional configuration for basic sharing scenarios. The library uses Android's Intent system, which provides built-in support for content sharing without requiring special permissions or manifest entries for basic text sharing.
Core Sharing Methods
The share() Method for Text and URLs
The primary method for sharing content in React Native is Share.share(), which opens a native share dialog containing the content you specify. This method accepts a content object with message and URL properties, along with optional parameters that control dialog behavior on different platforms.
The share method returns a Promise that resolves with an object containing the action taken by the user. The action property indicates whether the share was completed (Share.sharedAction) or dismissed (Share.dismissedAction). On iOS, when a share is successful, the activityType property identifies which application the content was shared to.
1import Share from 'react-native-share';2 3const shareMessage = async () => {4 try {5 const result = await Share.share({6 message: 'Check out this amazing React Native application!',7 });8 9 if (result.action === Share.sharedAction) {10 console.log('Content was shared successfully');11 } else if (result.activityType) {12 console.log(`Shared via: ${result.activityType}`);13 }14 } catch (error) {15 console.error('Share failed:', error.message);16 }17};When both message and URL are provided, the library combines them appropriately for each platform. On iOS, this typically results in a URL-preview card with accompanying text, while Android may display them separately depending on the receiving application.
1const shareWithUrl = async () => {2 try {3 await Share.share({4 message: 'Great resource for React Native developers:',5 url: 'https://reactnative.dev/docs/share',6 });7 } catch (error) {8 Alert.alert('Error', error.message);9 }10};The open() Method for File Sharing
For sharing files such as images, documents, or PDFs, React Native Share provides the Share.open() method. This method extends the basic sharing functionality to include file attachments, which is essential for applications that deal with media content or document management.
File paths must be accessible to the Share API, which means files should be stored in publicly accessible directories. On iOS, this typically includes the Documents directory and temporary caches, while Android requires files to be stored in external storage or shared content providers.
1import Share from 'react-native-share';2import { Platform, Alert } from 'react-native';3 4const shareFile = async (filePath, mimeType, fileName) => {5 try {6 const shareOptions = {7 url: Platform.OS === 'android'8 ? `file://${filePath}`9 : filePath,10 type: mimeType,11 filename: fileName,12 };13 14 const result = await Share.open(shareOptions);15 16 if (result.success) {17 console.log('File shared successfully');18 }19 } catch (error) {20 console.error('File share error:', error);21 }22};Sharing Multiple Files with shareMultiple
For applications that need to share multiple files simultaneously, such as sharing multiple images from a gallery or a collection of documents, React Native Share provides the shareMultiple method. This functionality is particularly valuable for social media applications, photo sharing apps, and document management systems. When building mobile applications that handle rich media, implementing efficient multi-file sharing becomes essential for user engagement.
1const shareMultipleFiles = async (filePaths) => {2 try {3 const files = filePaths.map(path => ({4 url: path,5 type: 'image/jpeg',6 filename: path.split('/').pop(),7 }));8 9 await Share.shareMultiple(files);10 } catch (error) {11 console.error('Multi-file share error:', error);12 }13};Validate file existence
Check that all files exist before attempting to share
Limit file count
Prevent memory issues by limiting the number of shared files
Provide feedback
Show user feedback during file preparation
Handle partial failures
Gracefully handle cases where some files are invalid
Platform-Specific Considerations
iOS Behavior and Limitations
iOS implements sharing through the UIActivityViewController, which presents a standardized share sheet with available sharing options. The platform enforces several constraints that developers must account for when implementing share functionality.
The iOS share dialog displays only applications installed on the device that can handle the shared content type. File sharing on iOS requires proper file path handling, as the sandboxed nature of iOS applications restricts file access to specific directories.
1await Share.share({2 message: 'Share this content',3}, {4 excludedActivityTypes: [5 'com.apple.UIKit.activity.CopyToPasteboard',6 'com.apple.UIKit.activity.Print',7 ],8});Android Behavior and Configuration
Android's sharing mechanism operates through the Intent system, which provides a flexible framework for inter-application communication. Understanding how Intents work is essential for implementing robust sharing functionality on Android.
Android applications declare their ability to receive shared content through intent filters in the AndroidManifest.xml file. When a share is initiated, the system presents an app chooser dialog that allows users to select their preferred sharing destination.
1const shareAndroidFile = async (filePath) => {2 if (Platform.OS === 'android') {3 await Share.open({4 url: filePath,5 type: 'application/pdf',6 });7 }8};Advanced Share Scenarios
iOS Share Extensions
For applications that need to appear in the iOS share sheet, implementing a Share Extension provides a seamless way for users to share content from other applications directly into your app. This advanced implementation requires native iOS code but enables powerful integration scenarios.
A Share Extension runs as a separate process from your main application, allowing it to interact with the share sheet while maintaining sandbox isolation. The extension receives shared content and can process it before sending it to your containing application through App Groups or other inter-process communication mechanisms.
Add Share Extension target
Create a new Share Extension target in Xcode
Configure Info.plist
Set up appropriate activity types for the extension
Implement ShareViewController
Create the controller to handle incoming content
Use App Groups
Share data between extension and main app
Implement deep linking
Pass data from extension to React Native
Android Intent Handling
Android's Intent system can also be configured to receive shared content from other applications. This involves adding intent filters to your AndroidManifest.xml that declare your application's ability to receive shared content.
1<intent-filter>2 <action android:name="android.intent.action.SEND" />3 <category android:name="android.intent.category.DEFAULT" />4 <data android:mimeType="text/plain" />5</intent-filter>1import { Linking, AppState } from 'react-native';2 3useEffect(() => {4 Linking.getInitialURL().then(url => {5 if (url) handleShareUrl(url);6 });7 8 const subscription = Linking.addEventListener('url', ({ url }) => {9 handleShareUrl(url);10 });11 12 return () => subscription.remove();13}, []);Error Handling and Best Practices
Common Error Scenarios
Implementing robust error handling is essential for creating reliable sharing functionality. React Native Share can fail for various reasons including file access issues, unavailable share targets, and platform-specific restrictions.
1const safeShare = async (content) => {2 try {3 const result = await Share.share(content);4 5 if (result.action === Share.sharedAction) {6 return { success: true, message: 'Shared successfully' };7 } else if (result.action === Share.dismissedAction) {8 return { success: false, message: 'Share cancelled by user' };9 }10 } catch (error) {11 if (error.message.includes('User did not share')) {12 return { success: false, message: 'Share was dismissed' };13 }14 if (error.message.includes('File not found')) {15 return { success: false, message: 'File not accessible' };16 }17 if (error.message.includes('Activity not found')) {18 return { success: false, message: 'No app available to handle share' };19 }20 return { success: false, message: 'Unknown error occurred' };21 }22};Always wrap share calls
Use try-catch blocks for all share operations
Provide meaningful feedback
Give users clear messages for each error type
Handle cancellation gracefully
Don't treat user cancellation as an error
Validate file access
Check file existence before attempting to share
Performance Optimization
Share operations can impact application performance if not implemented carefully, particularly when dealing with large files or multiple attachments. Following optimization strategies ensures a smooth user experience.
1const optimizedShare = async (imageUri) => {2 const compressedUri = await compressImageIfNeeded(imageUri);3 4 await Share.open({5 url: compressedUri,6 type: 'image/jpeg',7 });8 9 if (compressedUri !== imageUri) {10 await FileSystem.deleteAsync(compressedUri, { idempotent: true });11 }12};Prepare files ahead
Compress and prepare files before showing share dialog
Use image compression
Reduce file size for large photos
Clean up temporary files
Remove temporary files after sharing completes
Memoize components
Use React.memo() for share button components
User Experience Guidelines
Creating a positive sharing experience involves more than just functional code--it requires thoughtful UX design that guides users through the sharing process.
Clear share buttons
Use recognizable icons for sharing actions
Show loading states
Display feedback during file preparation
Confirm success
Provide confirmation after successful shares
Multiple options
Offer various sharing methods when relevant
Respect privacy
Be mindful of user privacy expectations
Test thoroughly
Test across different devices and OS versions
Conclusion
Implementing content sharing in React Native applications requires understanding both the library's capabilities and platform-specific behaviors. The React Native Share library provides a solid foundation for adding sharing functionality, with support for text, URLs, and files across both iOS and Android platforms.
By following the patterns and practices outlined in this guide, developers can create sharing experiences that enhance their applications' utility while respecting platform conventions and user expectations. For advanced use cases involving share extensions or custom intent handling, the investment in platform-specific implementation pays dividends through deeper integration with the mobile ecosystem.
Our web development services team specializes in building React Native applications with production-ready sharing functionality. We can help you implement robust sharing features that integrate seamlessly with your application architecture. Remember to always test sharing functionality on real devices, as simulator behavior may differ from actual user experience.
Sources
- React Native Share - GitHub Repository - Community-maintained library documentation
- React Native Official Documentation - Share - Core Share API specifications
- DEV Community: Share files on React Native - Practical file sharing implementation guide
- LogRocket: Sharing content in React Native apps - Best practices and error handling patterns
- Devas.life: Supporting iOS Share Extensions & Android Intents - Advanced share extension implementation