Giter Site home page Giter Site logo

obipawan / react-native-hyperlink Goto Github PK

View Code? Open in Web Editor NEW
796.0 4.0 76.0 5.91 MB

A <Hyperlink /> component for react-native that makes urls, fuzzy links, emails etc clickable

License: MIT License

JavaScript 24.60% TypeScript 75.40%
react react-native react-native-web hyperlink link fuzzy-links autolink url text

react-native-hyperlink's Introduction

react-native-hyperlink

NPM version Awesome

A <Hyperlink /> component for react-native & react-native-web that makes urls, fuzzy links, emails etc clickable

demo

Installation

npm i --save react-native-hyperlink

Props

name desc type default
linkify linkify-it object, for custom schema object require('linkify-it')()
linkStyle highlight clickable text with styles Text.propTypes.style
linkText A string or a func to replace parsed text oneOfType([ string, func ])
onPress Func to handle click over a clickable text with parsed text as arg func
onLongPress Func to handle long click over a clickable text with parsed text as arg func
linkDefault A platform specific fallback to handle onPress. Uses Linking. Disabled by default bool
injectViewProps Func with url as a param to inject props to the clickable component func i => ({})

Examples

Wrap any component that has <Text> (works for nested text too) in it

import Hyperlink from 'react-native-hyperlink'

export const defaultLink = () =>
  <Hyperlink linkDefault={ true }>
    <Text style={ { fontSize: 15 } }>
      This text will be parsed to check for clickable strings like https://github.com/obipawan/hyperlink and made clickable.
    </Text>
  </Hyperlink>

export const regularText = () =>
  <Hyperlink onPress={ (url, text) => alert(url + ", " + text) }>
    <Text style={ { fontSize: 15 } }>
      This text will be parsed to check for clickable strings like https://github.com/obipawan/hyperlink and made clickable.
    </Text>
  </Hyperlink>

export const regularTextLongPress = () =>
  <Hyperlink onLongPress={ (url, text) => alert(url + ", " + text) }>
    <Text style={ { fontSize: 15 } }>
      This text will be parsed to check for clickable strings like https://github.com/obipawan/hyperlink and made clickable for long click.
    </Text>
  </Hyperlink>

export const nestedText = () =>
  <Hyperlink onPress={ (url, text) => alert(url + ", " + text) }>
    <View>
      <Text style={ { fontSize: 15 } }>
        A nested Text component https://facebook.github.io/react-native/docs/text.html works equally well <Text>with https://github.com/obipawan/hyperlink</Text>
      </Text>
    </View>
  </Hyperlink>

export const highlightText = () =>
  <Hyperlink linkStyle={ { color: '#2980b9', fontSize: 20 } }>
    <Text style={ { fontSize: 15 } }>
      Make clickable strings like https://github.com/obipawan/hyperlink stylable
    </Text>
  </Hyperlink>

export const parseAndReplace = () =>
  <Hyperlink
    linkStyle={ { color: '#2980b9', fontSize: 20 } }
    linkText={ url => url === 'https://github.com/obipawan/hyperlink' ? 'Hyperlink' : url }
  >
    <Text style={ { fontSize: 15 } }>
      Make clickable strings cleaner with https://github.com/obipawan/hyperlink
    </Text>
  </Hyperlink>

export const passPropsText = () =>
  <Hyperlink
    linkDefault
    injectViewProps={ url => ({
          testID: url === 'http://link.com' ? 'id1' : 'id2' ,
          style: url === 'https://link.com' ? { color: 'red' } : { color: 'blue' },
          //any other props you wish to pass to the component
    }) }
  >
    <Text>You can pass props to clickable components matched by url.
        <Text>This url looks red https://link.com
    </Text> and this url looks blue https://link2.com </Text>
  </Hyperlink>

Dependenies

linkify-it

Development

PRs highly appreciated

License

MIT License

react-native-hyperlink's People

Contributors

ashoat avatar chrismllr avatar dabit1 avatar daisy1754 avatar derenge avatar gnl avatar justinffs avatar nicolaslopezj avatar obipawan avatar rangermauve avatar titozzz avatar xxsnakerxx 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

react-native-hyperlink's Issues

Emails not working on Android devices

Describe the bug
Tapping on mailto links on Android device is not opening mail apps. Working fine on iOS devices.

To Reproduce
Steps to reproduce the behavior:

  1. Click on mailto:[email protected]
  2. See blank screen

Expected behavior
Open default mail app or show mail app choices

Screenshots
Screenshot_20190416-110528

Smartphone (please complete the following information):

  • Device: Pixel 2
  • OS: Android Version 9
  • Browser: Default
  • Version: react-native-hyperlink 0.0.14

How to have multiple linkText?

How can i have multiple linkText in one Hyperlink component?

Trying to do it like the code below but it's not working.

<Hyperlink
              linkStyle={{ color: '#2980b9', fontSize: 14 }}
              linkText={url => (url === global.termsOfUse) ? 'Terms of Use' : url}
              linkText={url2 => (url === global.privacyPolicy) ? 'Privacy Policy' : url2}
            >
              <Text style={styles.inputTnC}>
              By continuing, i confirm that i have read and agree
              to the {global.termsOfUse} and {global.privacyPolicy}.
              </Text>
            </Hyperlink>

Does this library use WebView?

It doesn't look like it, but I just wanted to be sure. Apple doesn't accept apps with WebView anymore and I wouldn't want to get rejected at the last step if there's something I've missed.

export the Props

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

in some cases we need to export the Props

Here is the diff that solved my problem:

diff --git a/node_modules/react-native-hyperlink/index.d.ts b/node_modules/react-native-hyperlink/index.d.ts
index 135e70b..b2abf33 100644
--- a/node_modules/react-native-hyperlink/index.d.ts
+++ b/node_modules/react-native-hyperlink/index.d.ts
@@ -1,7 +1,7 @@
 import { Component } from 'react';
 import { StyleProp, TextStyle } from 'react-native';
 
-interface Props {
+ interface Props {
   linkDefault?: boolean;
   linkify?: object;
   linkStyle?: StyleProp<TextStyle>;
@@ -13,3 +13,4 @@ interface Props {
 declare class HyperLink extends Component<Props> {}
 
 export default HyperLink;
+export { Props as HyperLinkProps };

This issue body was partially generated by patch-package.

Tapping anywhere in original Text component triggers link

Tapping anywhere within the Text will trigger an onPress (in the below example).

It seems the last link declared in the passed Text component will be used when tapping anywhere. Video attached.

<Hyperlink 
  linkStyle={styles.linkStyles} 
  onPress={(url, text) => alert(`${url} -> ${text}`)}
>
  <View>
    <Text>{meeting.body}</Text>
  </View>
</Hyperlink>

Versions

"react": "16.3.0-alpha.1",
"react-native": "0.54.0",
"react-native-hyperlink": "^0.0.13"

hyperlinks-multiple

`linkify` prop is no longer optional

As of 0.17.0 that was released today, the library does no longer work when you do not provide a custom linkify-it object as a prop.

The problem is that the existing default value that gets set in the constructor gets unset by the getDerivedStateFromProps call here:

if (nextProps.linkify !== prevState.linkifyIt) {

A work-around for now is to always pass in the same default value from the outside.

Non Safari default browser links do not work

If your default browser is set to something aside from Safari -- links do not open.

To Reproduce
Steps to reproduce the behavior:

  1. Download Chrome and set it as a default browser
  2. Tap a link

Expected behavior
Links open

Smartphone (please complete the following information):

  • OS: 14+ -- maybe lower

Only works with https://

when I try to support pages with http: or simply with www..

Example

http://www.whatever.com
www.whatever.com

Does not works

I have used

inkDefs = {[
     {
         regex: /(www|http:|https:)+[^\s]+[\w]/g,
     }
]}

and now if it detects them. But when I press this links www.whatever.com, they do not work. I'm not sure is this is a android requirement, but would be good know the best way for fix it, because in my case i can't guaranteeing https to http in all links.

I have tried adding

 onPress: (orig, text, url) => {
      // I change url to orig, because url come undefined for me.
      HyperlinkedText._openWebUrl(orig);
}

but it does not work either

Padding breaks link

Using this in a with large padding breaks the link for some reason.

Sample:

<Hyperlink linkDefault={ true }>
  <Text style={{padding: 20}}>Testing https://www.google.com</Text>
</Hyperlink>

This was breaking links for me. Switching to margin fixed my use case but thought I'd put this here in case anyone else has a similar issue and can't find out why links aren't working.

Does not work for phone number

emailLink = () => (
    <Hyperlink
      onPress={this.emailCompany}
      linkText="[email protected]"
      linkStyle={{ color: "#2980b9" }}
    >
      <Label style={[styles.tabletStyleWithMarginTop]}>
        Email: [email protected]
      </Label>
    </Hyperlink>
  );

  phoneLink = () => (
    <Hyperlink
      onPress={this.callCompany}
      linkText="817-INT(732-3883)"
      linkStyle={{ color: "#2980b9" }}
    >
      <Label style={[styles.tabletStyleWithMarginTop]}>
        Phone: 817-INT(732-3883) , Select Option 2
      </Label>
    </Hyperlink>
  );

This is how I am calling it in my code

{this.phoneLink()}
 {this.emailLink()}

The email works but the phone number does not show the link.

Can anyone add this new feature: To get the link from the text

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

URL not detected when underscore exists in domain name

Describe the bug
URL not detected when underscore exists in domain name

To Reproduce
Steps to reproduce the behaviour:
Simple, just try any url with underscore in the domain name
for example: https://stocks_uhpavf.rpy.club/

Expected behavior
URL should be detected even when underscore exists in domain name

Using the latest version of this package 0.0.22
"react": "17.0.1",
"react-native": "0.65.3",

P.S: btw great package @obipawan, very helpful thanks.

Can't open hyperlink in Modal

Got this error when trying to open a link from a modal

Exception 'Application tried to present UIModalTransitionStylePartialCurl to or from non-fullscreen view controller <RCTModalHostViewController: 0x7fec0f84df90>.' was thrown while invoking open on target RNInAppBrowser with params (

Any suggestion? I can't change it to non modal

Text Input

Is your feature request related to a problem? Please describe.
I can't identify links through Text Input

Describe the solution you'd like
It would be amazing if it were possible to identify links through Text Input, just like Whatsapp

Using with react-native-web

I tried to use this package for web using react-native-web. But while building had an error:
ERROR in ./node_modules/react-native-hyperlink/dist/index.js
Module not found: Error: Can't resolve 'react-native' in '/.../web/node_modules/react-native-hyperlink/dist'.
Should I install the whole react-native package only to use react-native-hyperlink?

Color of normal text overrides link style

I have run into an issue while using this module with the child having a defined color. At the moment I have the <Hyperlink> component wrapping a single <Text> component. The <Hyperlink> component has the linkStyle prop defined with color: "blue". The <Text> component also has its color set on the style prop to some offshade of black. However the resulting text ends up being entirely in the <Text> components color. The color from the linkStyle prop is lost. Hope someone can help

hyperlink on press doesn't work on Android 12 but long press work

Hello,
i'm using react native hyperlink to extract links from text and redirect to links on press using react native Linking.openUrl() it work fine on IOS & old android version but it seems that it is not pressed on Android version 12
this is my code
note that long press is work in all devices also android 12
<HyperLink linkDefault={true} onLongPress={url => { Linking.openURL(url) }} onPress={(url) => { Linking.openURL(url) }} >
@obipawan

[IOS] No component found for view with name "RCTVirtualText"

Hey after RN upgrading to version 0.44, hyperlink stopped working. It crashes with this error:

[error][tid:com.facebook.react.ShadowQueue][RCTUIManager.m:1011] No component found for view with name "RCTVirtualText"

The code is:

<Hyperlink onPress={ url => alert(url) }>
	<Text>http://blabla.com</Text>
</Hyperlink>

The interesting part is that this is working fine:

<Hyperlink onPress={ url => alert(url) }>
	<Text>hello</Text>
</Hyperlink>

Any ideas?

image

Error thrown on null children

Consider the following where subtitle can be null/undefined, in which case we do not add a <Text> element for it:

<Hyperlink>
  <Text>{title}</Text>
  {subtitle && <Text>{subtitle}</Text>}
</Hyperlink>

This causes Hyperlink to throw en error Cannot read property 'type' of null.

I think this comes from the method parsing children, there is no safe-guard against null/undefined:

let { type : { displayName } = {} } = child

linkify example?

Hey there, thanks for making this library. I'm looking to do some twitter parsing and want to add a @name recognizer to add a link to it. I saw ou support linkify-it but I can't figure out what kind of object i'm supposed to pass. Any simple example you can provide would be super helpful. Thanks.

onHover for RN Windows

I've been playing with react-native-hyperlink on windows (as in react-native-windows), and one of the things I miss is an onHover handler. I understand this might not be interesting on platforms without pointers, but would you take a PR to add this if it's behind a platform selector?

Not linking custom domains

Describe the bug
React-native-hyperlink is not linking custom urls. For example "www.trusst.app" does not get linked.

To Reproduce
Steps to reproduce the behavior:
create a text within the Hyperlink tag with the text www.trusst.app

Expected behavior
The text should be clickable and formatted as designed.

Screenshots
Image from iOS

Smartphone (please complete the following information):
iOS(any)
Tested on iphone 6

Additional context

How to remove auto detect link?

Hi @obipawan, i have an issue when using your lib that i want to display a text
'Saya telah membaca dan menyetujui ketentuan penggunaan cinobile.com' and i just want to use hyperlink for the text 'ketentuan penggunaan' only. But when using your lib, it detected both the url 'cinobile.com'. How to remove auto detect link? Thanks in advance

Issues when hyperlink is nested

If the hyperlink component is nested under another touchable, both events fire. First the parent touchable fires, then the hyperlink fires. Anyway around this?

Throwing error with react-native 0.69.3

Describe the bug

Warning: Failed prop type: Hyperlink: prop type linkStyle is invalid; it must be a function, usually from the prop-types package, but received undefined.This often happens because of typos such as PropTypes.function instead of PropTypes.func.
at Hyperlink (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=njsolutions.watchpartys&modulesOnly=false&runModule=true:216800:22)

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

When used on Web, error about prop types appear.

Describe the bug
This error is given on Web:
Failed prop type: Hyperlink: prop type linkStyle is invalid; it must be a function, usually from the prop-types package, but received undefined. in Hyperlink (created by _default)

This happens because Text.propTypes is no longer a thing in latest RNW.

To Reproduce
Try using this package with latest RNW.

Expected behavior
No error should be logged

Additional info
I patched this in my own project by simply doing this:
linkStyle: _propTypes["default"].oneOfType([_propTypes["default"].object, _propTypes["default"].number]),

Any reason this would stop working with RN 0.36

I have used this for past few months but recently (as of yesterday) it became a lot less reliable. Not sure if this is because of an update or something else but now when I tap the links it only works like 25% of the times and it used to work all the time.

onPress not working properly on iPhone

Describe the bug
onPress not working properly on iPhone

To Reproduce
When we click on hyperlink it is not working properly
It is working although but not sometimes.

Expected behavior
Should call onPress when the user press on hyperlink

Smartphone (please complete the following information):

  • Device: iPhone 6,IPhoneX

Here is my code

{
    !this.state.isLoading && this.state.news.length > 0 && this.state.needToShowFullNews && 
< Hyperlink
    onPress = {
        (url, text) => this.openFullNews()
    }
    linkStyle = {
        {
            color: '#2980b9',
            fontSize: 20
        }
    }
    linkText = {
        url => url === 'https://github.com/obipawan/hyperlink' ? 'Read More' : url
    }
    injectViewProps = {
        url => ({
            testID: url === 'http://link.com' ? 'id1' : 'id2',
            style: url === 'https://link.com' ? {
                color: 'red'
            } : {
                color: 'blue'
            },
            //any other props you wish to pass to the component
        })
    }
}

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.