Deep linking not working when app is in background state React native
You need to register Linking listener for this case.
componentDidMount() {
Linking.addEventListener('url', this._handleOpenURL);
},
componentWillUnmount() {
Linking.removeEventListener('url', this._handleOpenURL);
},
_handleOpenURL(event) {
console.log(event.url);
}
For more https://facebook.github.io/react-native/docs/linking
Here's a version of Anurag's answer using hooks:
export function useDeepLinkURL() {
const [linkedURL, setLinkedURL] = useState<string | null>(null);
// 1. If the app is not already open, it is opened and the url is passed in as the initialURL
// You can handle these events with Linking.getInitialURL(url) -- it returns a Promise that
// resolves to the url, if there is one.
useEffect(() => {
const getUrlAsync = async () => {
// Get the deep link used to open the app
const initialUrl = await Linking.getInitialURL();
setLinkedURL(decodeURI(initialUrl));
};
getUrlAsync();
}, []);
// 2. If the app is already open, the app is foregrounded and a Linking event is fired
// You can handle these events with Linking.addEventListener(url, callback)
useEffect(() => {
const callback = ({url}: {url: string}) => setLinkedURL(decodeURI(url));
Linking.addEventListener('url', callback);
return () => {
Linking.removeEventListener('url', callback);
};
}, []);
const resetURL = () => setLinkedURL(null);
return {linkedURL, resetURL};
}
You can then use it with:
const {linkedURL, resetURL} = useDeepLinkURL();
useEffect(() => {
// ... handle deep link
resetURL();
}, [linkedURL, resetURL])
I added the function resetURL
because if a user shares the same file twice with the app, you would want to load it twice. However, because the deep link would end up being the same, so the useEffect
wouldn't be triggered again. You can cause it to be triggered again by setting the linkedURL
to null, so the next time a file is shared, you can be sure that it will cause the useEffect
to be run.
Also, I used decodeURI
to decode the passed in URL because if you use a library like react-native-fs to load the file from the specified path, it won't be able to handle files with spaces in their names unless you use decodeURI
.