Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native how to detect link form string and convert to a link?

Tags:

react-native

I'd like the user to be able to grab a link from a comment (string), similar to link.

Is there a simple way to do this?

I believe it is addressed here (https://github.com/facebook/react-native/issues/3148),

But I'm not quite sure how to implement it.

Thank you.

like image 514
skleest Avatar asked Jan 21 '16 20:01

skleest


2 Answers

You can use react-native-hyperlink:

import Hyperlink from 'react-native-hyperlink'
import {Text, Linking} from 'react-native'

const MyComponent = () => (
  <Hyperlink onPress={Linking.openURL}>
    <Text>{"Click on https://stackoverflow.com to test"}</Text>
  </Hyperlink>
)
like image 71
antoine129 Avatar answered Oct 16 '22 07:10

antoine129


I made a quick demo based on the component that was in the link.

I couldn't test LinkingIOS in that environment but these docs should get you there.

Here's the raw source:

var HyperText = React.createClass({

  render: function() {

    // Check if nested content is a plain string
    if (typeof this.props.children === 'string') {

      // Split the content on space characters
      var words = this.props.children.split(/\s/);

      // Loop through the words
      var contents = words.map(function(word, i) {

        // Space if the word isn't the very last in the set, thus not requiring a space after it
        var separator = i < (words.length - 1) ? ' ' : '';

        // The word is a URL, return the URL wrapped in a custom <Link> component
        if (word.match(/^https?\:\//)) {
          return <Link key={i} url={word}>{word}{separator}</Link>;
        // The word is not a URL, return the word as-is
        } else {
          return word + separator;
        }
      });
    // The nested content was something else than a plain string
    // Return the original content wrapped in a <Text> component
    } else {
      console.log('Attempted to use <HyperText> with nested components. ' +
                   'This component only supports plain text children.');
      return <Text>{this.props.children}</Text>;
    }

    // Return the modified content wrapped in a <Text> component
    return (
      <Text>
        {contents}
      </Text>
    );
  }

});

var Link = React.createClass({

  render: function() {
    return <Text onPress={this.openUrl.bind(this, this.props.url)}>{this.props.children}</Text>;
  },

  openUrl: function(url) {
    LinkingIOS.canOpenURL(url, (supported) => {
      if (!supported) {
        AlertIOS.alert('Can\'t handle url: ' + url);
      } else {
        LinkingIOS.openURL(url);
      }
    });
  }

});

Hope this somewhat helps.

like image 26
villeaka Avatar answered Oct 16 '22 07:10

villeaka