How does one Display a Hyperlink in React Native App?
JavascriptReact NativeJavascript Problem Overview
How do I display a hyperlink in a React Native app?
e.g.
<a href="https://google.com>Google</a>
Javascript Solutions
Solution 1 - Javascript
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';
Solution 2 - Javascript
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'
}
});
Solution 3 - Javascript
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>
Solution 4 - Javascript
Linking
:
React Native documentation suggests using
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.
Solution 5 - Javascript
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>
Solution 6 - Javascript
Use React Native Hyperlink (Native <A>
tag):
Install:
npm i react-native-a
import:
import A from 'react-native-a'
Usage:
<A>Example.com</A>
<A href="example.com">Example</A>
<A href="https://example.com">Example</A>
<A href="example.com" style={{fontWeight: 'bold'}}>Example</A>
Solution 7 - Javascript
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
Solution 8 - Javascript
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;
}
Solution 9 - Javascript
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>
Solution 10 - Javascript
the above code will make your text look like hyperlink
Solution 11 - Javascript
If you want to do links and other types of rich text, a more comprehensive solution is to use React Native HTMLView.
Solution 12 - Javascript
You can use linking property
Solution 13 - Javascript
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;
`
Solution 14 - Javascript
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
andLinking
withTouchableOpacity
, but the docs state thatPressable
is more "future-proof" thanTouchableOpacity
, so we usePressable
instead. Text
itself actually has anonPress()
property, soTouchableOpacity
is unnecessary for simply handling the press. However, it doesn't seem possible to implement the color style change withText
only.