I am using version 4.2.2 of react-native-render-html
. Given the following snippet:
# App.js
import React from 'react';
import HTML from 'react-native-render-html';
export default function App() {
return (
<HTML html='<a href="https://duckduckgo.com/">A Link To Press</a>' />
);
}
I would expect the web-browser to open when I press a link, but instead, nothing happens.
NB: I've updated my answer to include differences between versions
Because Linkin.canOpenUrl
has started requiring changing the android Manifest, there has been a bug preventing link press to open a browser in Android. This was fixed in version 6.3.4. So make sure to check your version!
Default behavior is to handle link press events with React Native Linking
API. If you need to customize link press handling, you should use renderersProps.a.onPress
prop.
import React from 'react';
import RenderHTML from 'react-native-render-html';
import { useWindowDimensions } from 'react-native';
const renderersProps = {
a: {
onPress(event, url, htmlAttribs, target) {
// Do stuff
}
}
}
export default function App() {
const { width } = useWindowDimensions();
return (
<RenderHTML
contentWidth={width}
source={{ html: '<a href="https://duckduckgo.com/">A Link To Press</a>' }}
renderersProps={renderersProps}
/>
);
}
In v5, pressing links is handled by Linking
API by default, and the behavior can be overridden by onLinkPress
prop. On v4, it is your responsibility to handle links. For that end, use onLinkPress
prop and Linking
utility from React Native. Be careful, if you're using Expo, you should import Linking
from expo-linking
.
import React from 'react';
import HTML from 'react-native-render-html';
import { Linking } from 'react-native';
// import * as Linking from 'expo-linking';
function openLink(event, url) {
Linking.openURL(url);
}
export default function App() {
return (
<HTML
html='<a href="https://duckduckgo.com/">A Link To Press</a>'
onLinkPress={openLink}
/>
);
}