How do I display a hyperlink in a React Native app?
e.g.
<a href="https://google.com>Google</a>
How do I display a hyperlink in a React Native app?
e.g.
<a href="https://google.com>Google</a>
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';
this.props.url
in place of 'http://google.com'
(no braces necessary)
Commented
Feb 14, 2017 at 5:12
import { Linking } from 'react-native';
in your document?
Commented
Jan 21, 2018 at 20:17
<Text>Some paragraph <Text onPress=...>with a link</Text> inside</Text>
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>
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'
}
});
Linking
:import { Linking } from 'react-native';
const url="https://google.com"
<Text onPress={() => Linking.openURL(url)}>
{url}
</Text>
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>
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>
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.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>
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
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;
}
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:
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>
If you want to do links and other types of rich text, a more comprehensive solution is to use React Native HTMLView.
You can use linking property <Text style={{color: 'skyblue'}} onPress={() => Linking.openURL('http://yahoo.com')}> Yahoo
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;
`
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;
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.