How to Add Hyperlinks in React Native

A hyperlink is a link that is activated or diverted by clicking on a highlighted word or image. Hyperlinks are not as common in mobile applications as you see in web applications. Still, hyperlinks are important in text-based mobile apps.

So, how to add hyperlinks easily in your react native app? First of all add react native hyperlink library to your project using the following command.

npm i --save react-native-hyperlink

Then import the library into your file as given below.

import Hyperlink from 'react-native-hyperlink';

Wrap the text component consists of links with the Hyperlink component.

<Hyperlink linkDefault={ true }>
    <Text style={ { fontSize: 15 } }>
      This text will be parsed to check for clickable strings like https://codingwithrashid.com and made clickable.
    </Text>
  </Hyperlink>

Making the prop linkDefault true prompts the link to open the browser when it is clicked. You can also use props such as onPress, onLongPress, linkStyle, linkText, etc. The linkText prop is very useful as you can define the link text of hyperlink easily, as given below.

<Hyperlink
    linkText={ url => url === 'https://codingwithrashid.com' ? 'Hyperlink' : url }
  >
    <Text style={ { fontSize: 15 } }>
      Make clickable strings cleaner with https://codingwithrashid.com
    </Text>
  </Hyperlink>

Following is the full example of react native hyperlink.

import React from 'react';
import {View, Text, StyleSheet} from 'react-native';
import Hyperlink from 'react-native-hyperlink';

const App = () => {
  return (
    <View style={styles.container}>
      <Hyperlink
        linkDefault
        linkStyle={{color: '#2980b9', fontSize: 20}}
        linkText={(url) =>
          url === 'https://codingwithrashid.com' ? 'reactnativeforyou' : url
        }>
        <Text style={styles.text}>
          Welcome to https://codingwithrashid.com blog. Here you get all react
          native tutorials!
        </Text>
      </Hyperlink>
    </View>
  );
};

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

export default App;

Following is the screenshot of the react native example.

react native hyperlink example

That’s how you add hyperlinks n react native easily.

Similar Posts

2 Comments

Leave a Reply