how to perform deep linking on React Native Navigation

2.3k views Asked by At

I have a request to implement deep linking in our React Native application whereby clicking a link will take them directly into the installed app. I am able to successfully direct them to the app. However, it must navigate to a certain page.

To address the problem, I use the code below. If there is a better approach to handle the problem, I would appreciate it if you could share it with me!

const useUrl = async () => {
   const url = await Linking.getInitialURL();
   if (url) {
      Navigation.push(componentId, {
        component: {
          name: 'screen',
        },
      });
   }
};

react-native and react-navigation both handle this as part of a feature set within the "Linking" that they offer. I can't find a way to handle that with React Native Navigation?

1

There are 1 answers

0
Heri Hakim Setiawan On

For me, I just add path to my stack navigator in react native like this

Product: {
 screen: ProductScreen,
 path: 'product/:productId'
},

and make sure your web that handle deep link have a similar path in routing. For example https://yourweb.com/product/:productId

And in your screen file, add this

useEffect(() => {
  Linking.addEventListener('url', _handleDeepLink)
  return () => {
    Linking.removeEventListener('url', _handleDeepLink);
  }
}

const _handleDeepLink = (event) => {
  if (event) {
    const route = event.url.replace(/.*?:\/\//g, '')
    const id = route.match(/\/([^\/]+)\/?$/)[1];
    if (id !== undefined) {
      // do your code here if screen just opened via deep link             
    }
  }
}