In React Native, the Linking module is the built-in interface used to interact with both incoming and outgoing app links. It allows you to open external URLs (like websites) or trigger system-level actions (like making a phone call or sending an email) using specific URL Schemes.
- Understanding URL Schemes (Protocols)
Every link you interact with has a Scheme (the part before the
://).
Your phone’s operating system uses this scheme to decide which app should handle the request.
2.Core Methods: openURL vs canOpenURL
Before you try to open a link, it is a best practice to check if the device actually has an app installed that can handle it.
Linking.canOpenURL(url): Returns a Promise that resolves to a boolean. It checks if there is an app installed that recognizes the scheme.
Linking.openURL(url): Attempts to open the link. If it fails (e.g., no email app is set up), it will throw an error.
Code Example: Phone & Email
Here is a reusable function to handle both "Call" and "Email" actions safely.
import { Linking, Alert, Platform } from 'react-native';
const handleExternalLink = async (url) => {
try {
const supported = await Linking.canOpenURL(url);
if (supported) {
await Linking.openURL(url);
} else {
Alert.alert("Error", `Don't know how to open this link: ${url}`);
}
} catch (error) {
Alert.alert("An error occurred", error.message);
}
};
- Usage Examples:
<Button title="Call Support" onPress={() => handleExternalLink('tel:+123456789')} />
<Button title="Email Us" onPress={() => handleExternalLink('mailto:hello@dev.com')} />
- Key Differences & Properties
_
tel: vs telprompt: (iOS Only)
_On iOS, if you use tel:, the phone dials immediately. If you use telprompt:, the system shows a confirmation popup first asking the user if they really want to call. Most developers prefer telprompt: for better UX on iPhone.
Email with Parameters
The mailto: scheme can be extended to include a subject and body using standard URL query parameters:
mailto:support@example.com?subject=Help&body=I need assistance
Top comments (0)