Giter VIP home page Giter VIP logo

react-native-deep-linking's Introduction

CI Status Coverage Version Downloads License Semantic Release Greenkeeper

Overview

React Native route-matching library to handle deep links.

Installation

This package is distributed via npm:

npm install react-native-deep-linking

Add deep link support to your app

For iOS:

1. Make sure you have a URL scheme registered for your app in your Info.plist

Scheme support

2. Add this to your AppDelegate.m

#import "RCTLinkingManager.h"

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
  return [RCTLinkingManager application:application openURL:url
                      sourceApplication:sourceApplication annotation:annotation];
}

// Only if your app is using [Universal Links](https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/AppSearch/UniversalLinks.html).
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity
 restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler
{
 return [RCTLinkingManager application:application
                  continueUserActivity:userActivity
                    restorationHandler:restorationHandler];
}

For Android:

https://developer.android.com/training/app-indexing/deep-linking.html

More info: https://facebook.github.io/react-native/docs/linking.html

Usage

1. Import DeepLinking

import DeepLinking from 'react-native-deep-linking';

2. Register schemes

DeepLinking.addScheme('example://');

3. Add event listener

import { Linking } from 'react-native';

Linking.addEventListener('url', handleUrl);

const handleUrl = ({ url }) => {
  Linking.canOpenURL(url).then((supported) => {
    if (supported) {
      DeepLinking.evaluateUrl(url);
    }
  });
};

4. Register routes

DeepLinking.addRoute('/test/:id', (response) => {
  // example://test/23
  console.log(response.id); // 23
});

5. Open external url (Optional)

If your app was launched from an external url registered to your app you can access and handle it from any component you want with

componentDidMount() {
  var url = Linking.getInitialURL().then((url) => {
    if (url) {
      Linking.openURL(url);
    }
  }).catch(err => console.error('An error occurred', err));
}

Example

import React, { Component } from 'react';
import { Button, Linking, StyleSheet, Text, View } from 'react-native';

import DeepLinking from 'react-native-deep-linking';

export default class App extends Component {
  state = {
    response: {},
  };

  componentDidMount() {
    DeepLinking.addScheme('example://');
    Linking.addEventListener('url', this.handleUrl);

    DeepLinking.addRoute('/test', (response) => {
      // example://test
      this.setState({ response });
    });

    DeepLinking.addRoute('/test/:id', (response) => {
      // example://test/23
      this.setState({ response });
    });

    DeepLinking.addRoute('/test/:id/details', (response) => {
      // example://test/100/details
      this.setState({ response });
    });

    Linking.getInitialURL().then((url) => {
      if (url) {
        Linking.openURL(url);
      }
    }).catch(err => console.error('An error occurred', err));
  }

  componentWillUnmount() {
    Linking.removeEventListener('url', this.handleUrl);
  }

  handleUrl = ({ url }) => {
    Linking.canOpenURL(url).then((supported) => {
      if (supported) {
        DeepLinking.evaluateUrl(url);
      }
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.container}>
          <Button
            onPress={() => Linking.openURL('example://test')}
            title="Open example://test"
          />
          <Button
            onPress={() => Linking.openURL('example://test/23')}
            title="Open example://test/23"
          />
          <Button
            onPress={() => Linking.openURL('example://test/100/details')}
            title="Open example://test/100/details"
          />
        </View>
        <View style={styles.container}>
          <Text style={styles.text}>{this.state.response.scheme ? `Url scheme: ${this.state.response.scheme}` : ''}</Text>
          <Text style={styles.text}>{this.state.response.path ? `Url path: ${this.state.response.path}` : ''}</Text>
          <Text style={styles.text}>{this.state.response.id ? `Url id: ${this.state.response.id}` : ''}</Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    fontSize: 18,
    margin: 10,
  },
});

Routes

The format of a deep link URL is the following: <scheme>://<host>/<path-component>

Example facebook://profile

// The following route matches the URL.
DeepLinking.addRoute('/profile', ({ scheme, path }) => {
  console.log(scheme); // `facebook://`
  console.log(path);   // `/profile`
});

// The following route does NOT match the URL.
DeepLinking.addRoute('profile', () => { ... });

Example facebook://profile/33138223345

// The following route matches the URL.
DeepLinking.addRoute('/profile/:id', ({ scheme, path, id }) => {
  console.log(scheme); // `facebook://`
  console.log(path);   // `/profile/33138223345`
  console.log(id);     // `33138223345`
});

Example facebook://profile/12/posts/403

// The following route matches the URL.
DeepLinking.addRoute('profile/:id/posts/:postId', ({ scheme, path, id, postId }) => {
  console.log(scheme); // `facebook://`
  console.log(path);   // `/profile/12/posts/403`
  console.log(id);     // `12`
  console.log(postId); // `403`
});

Regex Routes

Need something more powerful? You can add your own regex.

Example facebook://profile/123/details

const regex = /\/profile\/(.*)\/details/g;
DeepLinking.addRoute(regex, ({ scheme, path, match }) => {
  console.log(scheme); // `facebook://`
  console.log(path);   // `/profile/33138223345/details`
  console.log(match);  // `[ "/profile/123/details", "123" ]`
});

Contributing

Read up on our guidelines for contributing.

License

DeepLinking is licensed under the MIT License.

react-native-deep-linking's People

Contributors

greenkeeper[bot] avatar jonfridrik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-deep-linking's Issues

addEventListener is not working in IOS?

I have cloned your project and I tried to running your project in my local but I didn't work properly like addEventListener is not working.

Please let me what should I do?

An in-range update of husky is breaking the build 🚨

Version 0.13.3 of husky just got published.

Branch Build failing 🚨
Dependency husky
Current Version 0.13.2
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As husky is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ


Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details
Commits

The new version differs by 9 commits .

See the full diff.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

How to get full URL from addRoute callback/handler

I can't find a way to get the full URL inside a handler of addRoute method. I can only get scheme, path and URL params but I also need the domain. I've tried to use Linking.getInitialURL but it returns null everytime

Not working on android

When I try to open deeplink on the android application β€” the application is restarted continuously.

RN 0.36.1

this lib is not working with react-native version 0.63.3

no events are getting fire here is my code

`  componentDidMount() {
    // Google SignIn init
    GoogleUtil.configureGoogleSignIn();
// Register schemes
DeepLinking.addScheme('recreative://');
// Deep linking
Linking.addEventListener('url', this.handleUrl);

var url = Linking.getInitialURL()
  .then((url) => {
    if (url) {
      Linking.openURL(url);
    }
  })
  .catch((err) => console.error('An error occurred', err));

DeepLinking.addRoute('/UserProfile/:id', ({ scheme, path, id }) => {
  console.log('response for deeplinking');
  // recreative://UserProfile
  // this.setState({ response });
  console.log('scheme checking', scheme); // `facebook://`
  console.log('path checking', path); // `/profile/33138223345`
  console.log('id checking', id); // `33138223345`
  NavigationService.navigate('UserProfile');
});

// Twitter SignIn init
// TwitterUtil.init();

setTimeout(() => {
  SplashScreen.hide();
}, 2000);

}

  componentWillUnmount() {
    // Deep linking unmounting
    Linking.removeEventListener('url', this.handleUrl);

    // network info change remove listener
    NetworkInfo.removeNetworkInfoListener(
      this.state.store.dispatch,
      networkActions.networkInfoListener,
    );
  }
  handleUrl = (url) => {
    console.log('checking url', url);
    Linking.canOpenURL(url).then((supported) => {
      if (supported) {
        DeepLinking.evaluateUrl(url);
      }
    });
  };`

Best practice for catch all route?

Hi, thanks for your efforts with this repo.
Seem really solid!

If I want to catch all routes, especially those that doesn't match specified routes, what's the best way to go about it?

Thanks in advance, Anton

Query params inside last uri param

Hello!

Currently, this lib does not support query params.

What I mean is, suppose you have this route

DeepLinking.addScheme('domain://');
DeepLinking.addRoute('/queryparams/:id', ({id}) => console.log('id: ', id))

when evaluating the uri, id gets query params concatenated:

DeepLinking.evaluateUrl('domain://queryparams/1234?q=query&p=param');
// console.log => id: 1234?q=query&p=param

is there any way to get around this?

my intentions isn't to get the query params, but for them to not get concatenated to the last uri param.

probably in a next version, it would be nice for the addRoute callback to receive:

{ path, scheme, match, params, query }

I can send a PR with what I just wrote, but it would be a breaking change.

Cannot handle multiple params in a single url

Suppose an url like this myclnq://register?firstName=Saran&lastName=kumar, how can i get firstName and lastName from this url.
In the example, retrieing one param is defined but not multiple params. pls give a solution

An in-range update of eslint-plugin-react is breaking the build 🚨

The devDependency eslint-plugin-react was updated from 7.14.0 to 7.14.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint-plugin-react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v7.14.1

Fixed

  • Fix prop-types crash on multiple destructuring (#2319 @golopot)
Commits

The new version differs by 3 commits.

  • 62255af Update CHANGELOG and bump version
  • 655eb01 Merge pull request #2320 from golopot/issue-2319
  • 9639d82 [Fix] prop-types: fix crash on multiple destructuring

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Query params Deep link not working

Hi team , I am using this plugin for deeplink in my application my deeplink url as below
https://my.domain.com/services/auth/v1/unlock-account?token=1234

I set scheme and host in android as below

<data android:scheme="https" android:host="my.domain.com"/>

I write code in react native side as below

function addUnlockAccountRoute() {
     
    DeepLinking.addRoute('/services/auth/v1/unlock-account/:token', ({scheme, path, token}) => {
        console.log('unlock_account_deeplink_response_schema', scheme);
        console.log('unlock_account_deeplink_response_path', path);
        console.log('unlock_account_deeplink_response_token', token);
        
    });
  }

When i try to run above code route not found means i am not able to get value scheme, path and token value because my deep link URL includes query parmas like ?token=1234 so can you tell me how i can resolve this?

Reset Scheme Option ?

Can we also have reset scheme option? In Android, I am facing an issue where already running app is mounting scenes again on link open request and calling componentDidMount, which is pushing scheme again and causing routes callback to be called multiple times.

So I was hoping there will be some method like below to reset the scheme. Or is there already an option to reset schemes?

const resetScheme = () => { schemes.splice(0, schemes.length); };

If this is fine then, I can also send the pull request.

does this support deep linking into your app?

all of the examples show deep linking from your app into another app, for example - like launching facebook. how about deep linking into your own app? does this support that too?

Event listener not working on iOS

Simply does not react to any link being opened in the app.

This may be the react native Linking API issue too - I am not sure.

Not working in Simulator or physical device.

Version: 2.2.0
React Native: 0.63.4

Not working when the app closed [Android]

Hi,

How can I make this work while the app closed?

I've implement this and it's working when the app in foreground / background, but it's not working when the app closed. The listener only working when the app in foreground/background.

Really need help.

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.