How to open the browser when a link is pressed?

3.3k views Asked by At

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.

1

There are 1 answers

1
Jules Sam. Randolph On BEST ANSWER

NB: I've updated my answer to include differences between versions

Important note

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!

6.x

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}
        />
    );
}

5.x & 4.x

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}
        />
    );
}