214

How do I display a hyperlink in a React Native app?

e.g.

<a href="https://google.com>Google</a> 
2
  • 2
    Consider adding more tags like 'javascript' to get more attention from users. But do not over-generalize your posts by adding tags like 'coding', etc.
    – Matt C
    Commented May 29, 2015 at 23:07
  • 2
    @MattC I would argue that adding 'javascript' is too general. Commented May 7, 2020 at 3:53

16 Answers 16

427

Something like this:

<Text style={{color: 'blue'}}
      onPress={() => Linking.openURL('http://google.com')}>
  Google
</Text>

using the Linking module that's bundled with React Native.

import { Linking } from 'react-native';
7
  • 1
    If you need a dynamic value, you can use something like this.props.url in place of 'http://google.com' (no braces necessary)
    – Elon Zito
    Commented Feb 14, 2017 at 5:12
  • 3
    @devanshsadhotra do you have import { Linking } from 'react-native'; in your document? Commented Jan 21, 2018 at 20:17
  • 2
    You can embed <Text> elements too so that the linked text can be a portion of the parent text: <Text>Some paragraph <Text onPress=...>with a link</Text> inside</Text>
    – pstanton
    Commented Mar 21, 2018 at 4:53
  • 4
    LinkingIOS has been depreciated, use Linking. Commented Feb 12, 2019 at 23:42
  • 1
    use <touchableOpacity> just for a little animation when the text is clicked
    – Irfan wani
    Commented Feb 20, 2021 at 6:12
35

To do this, I would strongly consider wrapping a Text component in a TouchableOpacity. When a TouchableOpacity is touched, it fades (becomes less opaque). This gives the user immediate feedback when touching the text and provides for an improved user experience.

You can use the onPress property on the TouchableOpacity to make the link happen:

<TouchableOpacity onPress={() => Linking.openURL('http://google.com')}>
  <Text style={{color: 'blue'}}>
    Google
  </Text>
</TouchableOpacity>
0
34

The selected answer refers only to iOS. For both platforms, you can use the following component:

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

export default class HyperLink extends Component {

  constructor(){
      super();
      this._goToURL = this._goToURL.bind(this);
  }

  static propTypes = {
    url: PropTypes.string.isRequired,
    title: PropTypes.string.isRequired,
  }

  render() {

    const { title} = this.props;

    return(
      <Text style={styles.title} onPress={this._goToURL}>
        >  {title}
      </Text>
    );
  }

  _goToURL() {
    const { url } = this.props;
    Linking.canOpenURL(url).then(supported => {
      if (supported) {
        Linking.openURL(this.props.url);
      } else {
        console.log('Don\'t know how to open URI: ' + this.props.url);
      }
    });
  }
}

const styles = StyleSheet.create({
  title: {
    color: '#acacac',
    fontWeight: 'bold'
  }
});
3
23

React Native documentation suggests using Linking:

Reference

Here is a very basic use case:

import { Linking } from 'react-native';

const url="https://google.com"

<Text onPress={() => Linking.openURL(url)}>
    {url}
</Text>

You can use either functional or class component notation, dealers choice.

1
  • LinkingIOS has been depreciated, use Linking. Commented Feb 12, 2019 at 23:39
11

Another helpful note to add to the above responses is to add some flexbox styling. This will keep the text on one line and will make sure the text doesn't overlap the screen.

 <View style={{ display: "flex", flexDirection: "row", flex: 1, flexWrap: 'wrap', margin: 10 }}>
  <Text>Add your </Text>
  <TouchableOpacity>
    <Text style={{ color: 'blue' }} onpress={() => Linking.openURL('https://www.google.com')} >
         link
    </Text>
   </TouchableOpacity>
   <Text>here.
   </Text>
 </View>
8

Here's how to implement a hyperlink that appears underlined and has the web-standard behavior of changing colors when clicked (like CSS a:active).

import { Linking, Pressable, Text } from 'react-native';

  <Pressable onPress={() => Linking.openURL('https://example.com')}>
    {({ pressed }) =>
      <Text style={{
        textDecorationLine: 'underline',
        color: pressed ? 'red' : 'blue'
      }}>I'm a hyperlink!</Text>
    }
  </Pressable>
  • Some of the existing answers use Text and Linking with TouchableOpacity, but the docs state that Pressable is more "future-proof" than TouchableOpacity, so we use Pressable instead.
  • Text itself actually has an onPress() property, so TouchableOpacity is unnecessary for simply handling the press. However, it doesn't seem possible to implement the color style change with Text only.
5

Use React Native Hyperlink (Native <A> tag):

Install:

npm i react-native-a

import:

import A from 'react-native-a'

Usage:

  1. <A>Example.com</A>
  2. <A href="example.com">Example</A>
  3. <A href="https://example.com">Example</A>
  4. <A href="example.com" style={{fontWeight: 'bold'}}>Example</A>
3

for the React Native, there is library to open Hyperlinks in App. https://www.npmjs.com/package/react-native-hyperlink

In addition to this, i suppose you will need to check url and best approach is Regex. https://www.npmjs.com/package/url-regex

2
3

Just thought I'd share my hacky solution with anyone who's discovering this problem now with embedded links within a string. It attempts to inline the links by rendering it dynamically with what ever string is fed into it.

Please feel free to tweak it to your needs. It's working for our purposes as such:

This is an example of how https://google.com would appear.

View it on Gist:

https://gist.github.com/Friendly-Robot/b4fa8501238b1118caaa908b08eb49e2

import React from 'react';
import { Linking, Text } from 'react-native';

export default function renderHyperlinkedText(string, baseStyles = {}, linkStyles = {}, openLink) {
  if (typeof string !== 'string') return null;
  const httpRegex = /http/g;
  const wwwRegex = /www/g;
  const comRegex = /.com/g;
  const httpType = httpRegex.test(string);
  const wwwType = wwwRegex.test(string);
  const comIndices = getMatchedIndices(comRegex, string);
  if ((httpType || wwwType) && comIndices.length) {
    // Reset these regex indices because `comRegex` throws it off at its completion. 
    httpRegex.lastIndex = 0;
    wwwRegex.lastIndex = 0;
    const httpIndices = httpType ? 
      getMatchedIndices(httpRegex, string) : getMatchedIndices(wwwRegex, string);
    if (httpIndices.length === comIndices.length) {
      const result = [];
      let noLinkString = string.substring(0, httpIndices[0] || string.length);
      result.push(<Text key={noLinkString} style={baseStyles}>{ noLinkString }</Text>);
      for (let i = 0; i < httpIndices.length; i += 1) {
        const linkString = string.substring(httpIndices[i], comIndices[i] + 4);
        result.push(
          <Text
            key={linkString}
            style={[baseStyles, linkStyles]}
            onPress={openLink ? () => openLink(linkString) : () => Linking.openURL(linkString)}
          >
            { linkString }
          </Text>
        );
        noLinkString = string.substring(comIndices[i] + 4, httpIndices[i + 1] || string.length);
        if (noLinkString) {
          result.push(
            <Text key={noLinkString} style={baseStyles}>
              { noLinkString }
            </Text>
          );
        }
      }
      // Make sure the parent `<View>` container has a style of `flexWrap: 'wrap'`
      return result;
    }
  }
  return <Text style={baseStyles}>{ string }</Text>;
}

function getMatchedIndices(regex, text) {
  const result = [];
  let match;
  do {
    match = regex.exec(text);
    if (match) result.push(match.index);
  } while (match);
  return result;
}
3

Import Linking the module from React Native

import { TouchableOpacity, Linking } from "react-native";

Try it:-

<TouchableOpacity onPress={() => Linking.openURL('http://Facebook.com')}>
     <Text> Facebook </Text>     
</TouchableOpacity>
3

Solution:

The Below code uses 'Linking' which is used as a anchor tag for mobile in React Native. This will make your text look like a hyperlink.

'openURL' is a function used from Linking used to open the desired url which is passed into its parameter.

<TouchableOpacity onPress={()=>Linking.openURL('http://yahoo.com')}>
<Text style={{textDecorationLine:'underline',color:'blue}}>https://google.com</Text>
</TouchableOpacity>
0

If you want to do links and other types of rich text, a more comprehensive solution is to use React Native HTMLView.

2
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
    – Ari0nhh
    Commented Aug 2, 2016 at 4:47
  • @Ari0nhh I undeleted the question as it was the only way I could respond to your comment. There's lots of precedents on SO where a highly ranked answer is simply a link to a good library. Plus other answers already cover a simple implementation. I suppose I could repost this as a comment on the original question, but I do view it as a real answer. And leaving the link here is at least a crumb for future seekers, if people want to edit it and improve it with better examples at least now there's a place to start.
    – Eliot
    Commented Aug 2, 2016 at 21:05
0

You can use linking property <Text style={{color: 'skyblue'}} onPress={() => Linking.openURL('http://yahoo.com')}> Yahoo

0

I was able to use the following to align the touchable substring with the surrounding text. The fixed margin numbers are a bit hacky, but good enough if you don't need to use this with more than one font size. Otherwise you can pass the margins in as a prop along with the BaseText component.

import styled, { StyledComponent } from 'styled-components'
import { View, Linking, Text, TouchableOpacity } from 'react-native'

type StyledTextComponent = StyledComponent<typeof Text, any, {}, never>

export interface TouchableSubstringProps {
  prefix: string
  substring: string
  suffix: string
  BaseText: StyledTextComponent
  onPress: () => void
}

export const TouchableSubstring = ({
  prefix,
  substring,
  suffix,
  BaseText,
  onPress,
}: TouchableSubstringProps): JSX.Element => {
  const UnderlinedText = styled(BaseText)`
    text-decoration: underline;
    color: blue;
  `

  return (
    <TextContainer>
      <Text>
        <BaseText>{prefix}</BaseText>
        <TextAlignedTouchableOpacity onPress={onPress}>
          <UnderlinedText>{substring}</UnderlinedText>
        </TextAlignedTouchableOpacity>
        <BaseText>{suffix}</BaseText>
      </Text>
    </TextContainer>
  )
}

const TextContainer = styled(View)`
  display: flex;
  flex: 1;
  flex-direction: row;
  flex-wrap: wrap;
  margin: 10px;
`

const TextAlignedTouchableOpacity = styled(TouchableOpacity)`
  margin-top: 1px;
  margin-bottom: -3px;
`

0
import React from 'react';
import { TouchableOpacity, Text, Linking } from 'react-native';

const MyLink = () => {
  const handlePress = () => {
    Linking.openURL('https://google.com');
  };

  return (
    <TouchableOpacity onPress={handlePress}>
      <Text style={{ color: 'blue' }}>Google</Text>
    </TouchableOpacity>
  );
};

export default MyLink;
0

You can check this repo https://github.com/Tarikmnk/ReactHyperText It makes username, hashtag and URL hyped. If you want you can add your own types as well.

1
  • A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it is there, then quote the most relevant part of the page you are linking to in case the target page is unavailable.
    – cursorrux
    Commented Apr 25 at 7:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.