How to Open external URL in Web Browser in React Native

Last Updated on December 13, 2020.

Sometimes, you may want to open a url in the web browser of the device. You can use Linking api from react native which is used for managing the interaction with incoming and outgoing links.

With Linking API, you can open a url through the default browser of the device. You just need to invoke openURL method to open the external url.

Linking.openURL(url).catch((err) => console.error('An error occurred', err));

Go through the react native example below where reactnativeforyou blog is opened when the app is launched.

Class based component

//import liraries
import React, { Component } from 'react';
import { View, Text, StyleSheet, Linking } from 'react-native';

// create a component
const URL = "https://reactnativeforyou.com"
class MyClass extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>MyClass</Text>
      </View>
    );
  }
  componentDidMount(){
    Linking.openURL(URL).catch((err) => console.error('An error occurred', err));
  }
}



// define your styles
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#2c3e50',
  },
});

//make this component available to the app
export default MyClass;

Function based component

import React, {useEffect} from 'react';
import {View, Text, StyleSheet, Linking} from 'react-native';

const URL = 'https://reactnativeforyou.com';
const App = () => {
  useEffect(() => {
    Linking.openURL(URL).catch((err) =>
      console.error('An error occurred', err),
    );
  });

  return (
    <View style={styles.container}>
      <Text>MyClass</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#2c3e50',
  },
});

export default App;
react native external url

Leave a Reply

%d bloggers like this: