🚪 Linking & Deep Links in React Native
Opening Doors to Your App from Anywhere!
🎯 The Big Picture: What Are We Learning?
Imagine your app is a house with special magic doors. These doors can:
- Open websites (like knocking on someone else’s door)
- Let others knock on YOUR door and come right to a specific room
- Work on both iOS and Android—like having universal keys!
This is what Linking does in React Native. Let’s explore!
🔑 The Linking API: Your Magic Key Ring
Think of the Linking API as a key ring that lets you:
- Open other apps (like opening a browser or email)
- Listen for visitors (when someone tries to enter your app)
- Check the entrance (see how someone arrived)
Your Key Ring in Code
import { Linking } from 'react-native';
// Your key ring is ready!
// Now you can open doors and
// welcome visitors
The Linking API gives you these magic powers:
openURL()— Open a door to somewhere elsecanOpenURL()— Check if a door existsgetInitialURL()— See which door someone used to enteraddEventListener()— Listen for knocks at your door
🌐 Opening URLs: Knocking on Other Doors
Sometimes your app needs to visit other places—like opening a website, making a phone call, or sending an email.
The Magic Spell
import { Linking } from 'react-native';
// Open a website
const openWebsite = async () => {
const url = 'https://google.com';
// First, check if door exists
const canOpen = await Linking.canOpenURL(url);
if (canOpen) {
await Linking.openURL(url);
} else {
console.log("This door doesn't exist!");
}
};
Different Types of Doors
| What You Want | URL Format | Example |
|---|---|---|
| Website | https://... |
https://google.com |
| Phone Call | tel:... |
tel:+1234567890 |
| Send Email | mailto:... |
mailto:hi@mail.com |
| Send SMS | sms:... |
sms:+1234567890 |
| Open Settings | Platform-specific | See below |
Opening Phone Settings
// Open app settings
Linking.openSettings();
// This takes users to YOUR app's
// settings page in the phone!
🏠 Deep Linking Setup: Building Your Magic Doors
Now for the exciting part! Let’s build doors INTO your app so others can visit specific rooms (screens).
What is a Deep Link?
A deep link is like giving someone directions to a specific room in your house, not just the front door.
Normal link: myapp:// (front door)
Deep link: myapp://profile (straight to bedroom!)
Step 1: Choose Your App’s Name
First, pick a URL scheme—your app’s special name:
myapp://
coolshop://
learningapp://
Step 2: Tell Your App to Listen
import { Linking } from 'react-native';
import { useEffect } from 'react';
function App() {
useEffect(() => {
// Check if app was opened via link
const checkInitialURL = async () => {
const url = await Linking.getInitialURL();
if (url) {
handleDeepLink(url);
}
};
checkInitialURL();
// Listen for links while app is open
const subscription = Linking.addEventListener(
'url',
({ url }) => handleDeepLink(url)
);
return () => subscription.remove();
}, []);
return <YourApp />;
}
🎯 Deep Link Handling: Welcoming Your Visitors
When someone uses your magic door, you need to:
- See which door they used
- Take them to the right room
The Visitor Greeter
const handleDeepLink = (url) => {
// url might be: myapp://profile/123
// Parse the URL
const route = url.replace('myapp://', '');
// route is now: profile/123
const [screen, id] = route.split('/');
// screen = 'profile', id = '123'
// Now navigate!
if (screen === 'profile') {
navigation.navigate('Profile', { userId: id });
} else if (screen === 'product') {
navigation.navigate('Product', { productId: id });
}
};
A Complete Flow Diagram
graph TD A["User clicks link"] --> B{App running?} B -->|No| C["App launches"] B -->|Yes| D["URL event fires"] C --> E["getInitialURL"] D --> F["addEventListener catches it"] E --> G["handleDeepLink"] F --> G G --> H["Navigate to screen"]
🍎 Universal Links (iOS): The Fancy Front Door
Universal Links are like having a verified, official entrance to your house. Apple says “Yes, this is the REAL house!”
Why Universal Links?
| Regular Deep Link | Universal Link |
|---|---|
myapp://profile |
https://myapp.com/profile |
| Works only if app installed | Falls back to website if no app |
| Less trusted | Verified by Apple |
Setup Checklist
Step 1: Create apple-app-site-association file
Host this on your website (no file extension!):
{
"applinks": {
"apps": [],
"details": [
{
"appID": "TEAMID.com.yourapp",
"paths": ["/profile/*", "/product/*"]
}
]
}
}
Step 2: Add to Xcode
In your iOS project:
- Open Xcode
- Go to Signing & Capabilities
- Click + Capability
- Add Associated Domains
- Enter:
applinks:yourwebsite.com
Step 3: Update Info.plist
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>myapp</string>
</array>
</dict>
</array>
How It Works
graph TD A["User taps https://myapp.com/profile"] --> B{App installed?} B -->|Yes| C["Opens app directly"] B -->|No| D["Opens in Safari"] C --> E["Navigate to Profile screen"]
🤖 App Links (Android): The Robot’s Way
App Links are Android’s version of Universal Links. Same idea—verified, official doors!
Setup Checklist
Step 1: Create assetlinks.json
Host at: https://yourwebsite.com/.well-known/assetlinks.json
[{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": {
"namespace": "android_app_namespace",
"package_name": "com.yourapp",
"sha256_cert_fingerprints": [
"YOUR:SHA256:FINGERPRINT:HERE"
]
}
}]
Step 2: Update AndroidManifest.xml
<activity
android:name=".MainActivity"
android:launchMode="singleTask">
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data
android:scheme="https"
android:host="yourwebsite.com"
android:pathPrefix="/profile"/>
</intent-filter>
</activity>
Get Your SHA256 Fingerprint
# In terminal, run:
cd android && ./gradlew signingReport
Look for the SHA256 value in the output!
🎮 Putting It All Together
Here’s a complete example that handles all types of links:
import { Linking } from 'react-native';
import { useEffect } from 'react';
function App({ navigation }) {
const handleDeepLink = (url) => {
if (!url) return;
// Handle different URL patterns
// myapp://profile/123
// https://myapp.com/profile/123
let path = url;
// Strip scheme
if (url.includes('://')) {
path = url.split('://')[1];
}
// Strip domain if present
if (path.includes('myapp.com/')) {
path = path.replace('myapp.com/', '');
}
// Now parse the path
const parts = path.split('/');
const screen = parts[0];
const id = parts[1];
// Navigate!
switch(screen) {
case 'profile':
navigation.navigate('Profile', { id });
break;
case 'product':
navigation.navigate('Product', { id });
break;
default:
navigation.navigate('Home');
}
};
useEffect(() => {
// App opened via link
Linking.getInitialURL().then(handleDeepLink);
// App already open, link clicked
const sub = Linking.addEventListener('url',
({ url }) => handleDeepLink(url)
);
return () => sub.remove();
}, []);
return <YourApp />;
}
📋 Quick Reference
| Task | Code |
|---|---|
| Open URL | Linking.openURL(url) |
| Check if can open | Linking.canOpenURL(url) |
| Get launch URL | Linking.getInitialURL() |
| Listen for URLs | Linking.addEventListener('url', handler) |
| Open settings | Linking.openSettings() |
🎉 You Did It!
You now understand:
- ✅ Linking API — Your key ring for opening and listening
- ✅ Opening URLs — Visiting websites, making calls, sending emails
- ✅ Deep Linking Setup — Building magic doors into your app
- ✅ Deep Link Handling — Welcoming visitors to the right room
- ✅ Universal Links (iOS) — Apple’s verified official doors
- ✅ App Links (Android) — Google’s verified official doors
Your app now has magic doors that work everywhere! 🚪✨
