Open a Webpage in React Native with Linking and WebView

Chris Achard
InstructorChris Achard

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 5 years ago

There are two ways to open urls in React Native. One is to open, and switch to the device's web browser, and the other is to embed the web page within your application.

To open the mobile device's web browser, we'll import Linking from react native, and use the openURL function, which will open any url that starts with http or https in that web browser.

If you want to stay within your current application however, you can import WebView from react native, and use that as a component in your application. Pass in a uri param to display that web page in the embedded web view.

Instructor: [00:00] To use a button in your app to open a web page on the device's web browser, import linking from React Native. Linking, let see open other apps that may be installed on the phone, including the browser.

[00:13] In the on press of the touchable element, call Linking.openURL, and you can pass a valid URL to open it. Now, tapping a link will switch apps to the built-in web browser.

[00:31] If you don't want to open the device's browser, but instead you want to open a URL without leaving your app, you first need to make a new screen in your application.

[00:40] We'll call that file, browser. Import React and component from React, and view from React Native. Also, import web view from React Native, which is what we'll used to display the web page.

[00:58] We'll display a view and make sure to flex it to take up the entire page. Then, add the web view component. We'll be using React navigation's params to set the URL for the web view, which will come in under the navigation's state.params.url.

[01:14] Also, be sure to flex the web view to take up the entire screen. We want to be able to go back to the previous screen from this screen, so put in a header with a back button that calls navigation.goBack.

[01:34] Then, add that screen to the navigation stack in app.js. Now back where the link is, we can navigate to the new browser screen, and pass the URL to display in the web view to the navigate function. React navigation will make that available in the component's props.

[01:54] When we run the app and press the link, the browser's screen is pushed on to the navigation's stack. It shows the web page directly on that screen without leaving the current app.