An Error Occurred Please Try Again Later Youtube Webview in Simulator

As a React Native programmer, you may be asked to implement features similar redirecting to a spider web page or a different app within your React Native app. This can be accomplished past using two modules from the React Native API: WebViews
and Linking
.
The WebView
component in React Native cadre start became available in React Native version 0.57.x
. Right now it is available as a community module and is ofttimes a default manner to let the user visit external links inside an iOS or an Android application.
The Linking
module allows y'all to handle deep links that can lead to other applications or utilise a native browser of the device. Nosotros'll show you both the WebView
component and the Linking
module in action beneath.
Prerequisites
To follow this tutorial, make certain you lot have the following installed:
- NodeJS (>=
viii.x.x
) with npm or yarn installed equally a package director - expo-cli (>=
iii.0.4
), previously known as create-react-native-app - JavaScript/ES6 basics
Please note that, throughout this tutorial, we'll be using an iOS simulator to demonstrate the application.
Table of Contents
- Setting up a Crowdbotics app
- Setting up the React Native app
- Creating a uncomplicated WebView
- Adding Navigation between two screens
- Completing the WebView Screen
- Linking to other apps
- Handling deep links
- Conclusion
Setting upwardly a Crowdbotics app
In this section, you volition be setting up a Crowdbotics project that has React Native and an Expo generated template with stable and current dependencies for you to leverage. At the time of writing this tutorial, the template is based on Expo SDK version 32
. So instead of going into too much hassle virtually upgrading this React Native app, I will exist walking you through creating a new React Native projection in the next department.
To follow along, setting upwards a new project using Crowdbotics app builder service is easy. Visit the app.crowdbotics.com dashboard. Once you are logged in, choose Create New Application.

On the Create an Application page, cull React Native Expo template under Mobile App. Lastly, select the name of your app at the bottom of the page then click the button Create my app!
After a few moments, your Crowdbotics project volition exist created. Upon its creation, it volition redirect yous to the app dashboard, where you can see a link to GitHub, Heroku, and Slack. Once your project is created, y'all volition go an invitation from Crowdbotics to download your project or clone the repository from GitHub either via e-mail or as a notification if you logged in using GitHub authentication.
Crowdbotics provides out-of-the-box solutions, including support and development of your application.
Setting up the React Native app
Once the app is generated and bold yous take either downloaded the project or cloned it in your local dev environment, navigate inside the directory. You will be welcomed by two sub-directories: backend
and frontend
. For this tutorial, you tin ignore the backend
directory and open the frontend
directory in your favorite lawmaking editor or IDE.

One of the main reasons to utilize Expo for this tutorial is to have faster evolution setup. Crowdbotics' Expo app by default comes with a set of unremarkably used libraries in the React Native ecosystem. Some of these libraries are:
-
react-navigation
which you are going to encounter in activeness later -
native-base of operations
, 1 of the most popular UI component libraries -
redux
to manage the application's state
Y'all tin find the complete list of all the dependencies the project relies on inside the package.json
file. Now, to install these dependencies, execute the below command.
yarn install # or npm install
Later installing all the dependencies, run the command yarn run start
and make sure either a simulator is running, or a real device is continued.
In this tutorial, you are not going to make use of Login
or Signup
screens that are provided past the Crowdbotics app. Let united states of america make some changes in the navigation flow such that whenever the app reboots, it straight opens HomeScreen
equally the first screen.
Open up the src/navigators/HomeNavigator.js
file and change it as follows:
import { createStackNavigator, createAppContainer } from 'react-navigation' import Dwelling from '../containers/Home' const HomeNavigator = createStackNavigator({ Home: { screen: Home, navigationOptions: { header: cipher } } }) const HomeRootNavigator = createAppContainer(HomeNavigator) export default HomeRootNavigator
In the above snippet, y'all are defining the HomeNavigator
as the root level app container. This navigator is based on StackNavigation
which is going to be useful when adding WebViews
.
Import the newly created HomeRootNavigator
inside the file App.js
. Supercede the existing AppNavigator
with HomeRootNavigator
as shown in the snippet below.
import React, { Component } from 'react' import { StatusBar } from 'react-native' import { Provider } from 'react-redux' import HomeRootNavigator from './src/navigators/HomeNavigator' import store from './src/redux/shop' form App extends Component { render() { return ( <Provider store={shop}> <StatusBar barStyle='light-content' /> <HomeRootNavigator /> </Provider> ) } } export default App
Now, when the app runs, you will exist welcomed past the following Habitation screen, which is the default screen in Crowdbotics Expo generated apps.

Creating a elementary WebView
To create a simple WebView component, all you accept to practise is import the WebView
component from React Native core within the file src/containers/Home/index.js
file.
import React from 'react' import { WebView } from 'react-native'
Then modify the functional Dwelling house
component in the same file with the following WebView
component.
const Domicile = () => <WebView source={{ uri: 'https://blog.crowdbotics.com' }} /> export default Home
The WebView
component requires a source
prop to load the static HTML in the class of a web page or a URI from a remote source where the web page already exists. You will become the following issue.

Adding Navigation betwixt two screens
In the previous sit-in, you can clearly observe that the WebView
component is currently loading the Crowdbotics blog from the URI. However, it's missing some basic navigation mechanisms, such as how to go out the Web view way when the user is done interacting with the web folio and become dorsum to the application.
To enhance the current catamenia, in this section, you are going to add some other container screen in the stack navigator that is going to take care of displaying the spider web view.
Create a new sub-directory inside src/containers
chosen WebViewScreen
. Next, inside this directory, create a new file called index.js
with the following lawmaking snippet. This component, for now, will act every bit a mock component for now.
import React, { Component } from 'react' import { StyleSheet, View, Text } from 'react-native' class WebViewScreen extends Component { render() { return ( <View fashion={styles.container}> <Text style={styles.text}>Webview Screen</Text> </View> ) } } const styles = StyleSheet.create({ container: { flex: ane, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center' }, text: { color: '#333', textAlign: 'centre' } }) export default WebViewScreen
You should also change the Habitation
component. At that place is going to be a back button that will help navigate from the Home
screen to the WebViewScreen
when the navigation is added.
import React, { Component } from 'react' import { Container, Content, Text, Button } from 'native-base' import styles from './styles' class Home extends Component { country = { title: 'Crowdbotics Web log', link: 'https://weblog.crowdbotics.com' } handleButtonPress() { alert('You clicked') } return() { const { championship } = this.state return ( <Container style={styles.container}> <Content contentContainerStyle={styles.content}> <Button onPress={this.handleButtonPress} way={styles.button}> <Text manner={styles.text}>{championship}</Text> </Push button> </Content> </Container> ) } } consign default Home
In the above snippet, notice that the initial country object holds two properties: championship
and link
. The title
is going to be displayed on the push button equally the text, and the link
is going to be passed to the WebViewScreen
to open the spider web page. Now run the application, and on the Abode screen, there will be a push.

Clicking the button won't practise any practiced for now. Then allow us add the navigation betwixt the 2 screens, such that y'all can laissez passer the navigational props.
Get to navigators/HomeNavigator.js
file and allow us add the WebViewScreen
component.
import { createStackNavigator, createAppContainer } from 'react-navigation' import Abode from '../containers/Home' import WebViewScreen from '../containers/WebViewScreen' const HomeNavigator = createStackNavigator({ Domicile: { screen: Habitation, navigationOptions: { header: zero } }, WebViewScreen: { screen: WebViewScreen, navigationOptions: () => ({ headerTintColor: '#fff', headerStyle: { backgroundColor: '#0a1142' } }) } }) const HomeRootNavigator = createAppContainer(HomeNavigator) export default HomeRootNavigator
Stack Navigation provides a way to transit betwixt screens. This mechanism works quite similar to how a web application works in a web browser. A spider web app either pushes (next page) or pops (go dorsum) when navigating betwixt unlike web pages in a browser. Similarly, different screens combined together are used to either push button or pop in a React Native awarding using the stack navigation mechanism.
You will get the following consequence.

Notice that Stack Navigator from react-navigation
adds a default header if not specified. The WebViewScreen
utilizes this header
to navigate back to the Home
screen by clicking the dorsum
button.
As the navigation between the ii screens is working now, permit's apply navigation params to send the title from the Dwelling house
component's land to the WebViewScreen
. First, within the HomeNavigator.js
file, modify navigationOptions
of WebViewScreen
past passing a navigation
argument and add together a title
holding to information technology.
WebViewScreen: { screen: WebViewScreen, navigationOptions: ({ navigation }) => ({ title: navigation.state.params.championship, // rest remains same }) }
Next, go to the Home/index.js
file and laissez passer the title
from the initial state every bit an object that is the second parameter to the navigation props.
handleButtonPress = () => { const { title } = this.state this.props.navigation.navigate('WebViewScreen', { championship }) }
The navigation.state.params
allows reading the parameters passed through when handling the push press in the Home screen component. The props.navigation.navigate
is used to figure out which screen or route to visit when the button is pressed on the dwelling house screen. The name of the route or the screen is passed as the first argument as you tin can observe in the higher up snippet.
At present go back to the simulator device, and you will observe that the header on WebViewScreen
shows the title of the web page.

Completing the WebView Screen
Open the WebViewScreen.js
component file and edit information technology with simply one WebView
component beingness returned inside the render
method.
import React, { Component } from 'react' import { WebView, ActivityIndicator } from 'react-native' class WebViewScreen extends Component { LoadingIndicatorView() { render ( <ActivityIndicator color='#0a1142' size='big' fashion={{ flex: 1, justifyContent: 'center' }} /> ) } render() { const { params } = this.props.navigation.country return ( <WebView source={{ uri: params.link }} renderLoading={this.LoadingIndicatorView} startInLoadingState={true} /> ) } } export default WebViewScreen
The WebView
component from React Native uses props like startInLoadingState
and renderLoading
, which triggers the loading indicator—in our case, the part LoadingIndicatorView()
. This loading indicator is a pragmatic approach when a web page takes time to load.
Likewise note that in the higher up snippet, you will find another way to pass data between ii screens. The WebViewScreen
is using navigation.state.params
to become the link
from the Home screen's initial land.
Volition it work? The elementary answer is no. Why? Considering in the Dwelling house
screen component, yous are not passing the link
notwithstanding equally the second argument for the WebViewScreen
component to render its value.
Edit the following line inside Dwelling house/alphabetize.js
component.
handleButtonPress = () => { const { title, link } = this.state this.props.navigation.navigate('WebViewScreen', { title, link }) }
Now, go back to the simulator and press the button. Information technology opens a new screen that displays the Crowdbotics' blog.

Y'all meet, it does take time to load the consummate web folio, and ActivityIndicator
component helps to display a spinner to convey the same message to the end-user of the application. This completes the WebView
section.
Linking to other apps
The WebView
component is great to render a 3rd-political party website within a React Native app. In the previous sections, y'all learned how to create and utilize the component from React Native's core.
As a mobile developer, there are going to be scenarios where y'all'll want to open the website or the link in the device's native browser or other native awarding. In these scenarios, you cannot utilise WebViews
. Also, these scenarios are known as deep linking and are more common in mobile applications.
React Native's cadre API provides some other module called Linking
. This module allows interacting with other applications via deep links. Information technology provides helper methods set to employ deep links in your current application. In the post-obit sections, you are going to see it in activeness.
Open the Home/index.js
file and modify the initial land object. The object now contains an assortment called links
with three different items. Each item contains properties like championship
to display the text on the button, and link
to designate the URI to follow when the button is clicked.
country = { links: [ { title: 'Native Browser', link: 'https://weblog.crowdbotics.com' }, { title: 'Text Bulletin', link: 'sms:+9910000000' }, { title: 'Email', link: 'mailto:[email protected]' }, { title: 'YouTube', link: 'https://www.youtube.com/spotter?v=ypdk64ySgoo&listing=PLSk21zn8fFZBKEJxmkdSzzmMJrxkfyjph' } ] }
Afterwards modifying the initial state, let u.s. motion to the return part and display four buttons past mapping over the state.links
array. To avert the alarm in a yellowish box, too add a key
prop to the Button
component. This prop will employ the alphabetize
value since there is no unique identifier associated with whatever of the items in the links
array.
render() { const { links } = this.state render ( <Container style={styles.container}> <Content contentContainerStyle={styles.content}> {links.map((item, alphabetize) => ( <Push onPress={() => this.handleButtonPress(particular)}} fashion={styles.button} key={alphabetize}> <Text manner={styles.text}>{item.championship}</Text> </Button> ))} </Content> </Container> ) }
Apart from traversing the array, the rest of the code remains the aforementioned. You will get the following result on a device.

Treatment Deep Links
From the previous section, you know that whenever the user presses the button for each link, it will use the helper method chosen handleButtonPress
and laissez passer the correct item from the state.links
array. This argument particular
that is passed is then received by the handleButtonPress
every bit shown below.
handleButtonPress = particular => { Linking.openURL(particular.link).catch(err => console.mistake('An error occurred', err) ) }
Linking
module has a method to open external links. These external links can vary in nature, such as nosotros have defined in the state of the Dwelling
component. In the code snippet above, the method openURL
requires a valid URL to be passed for it to work. This method is promise-based, so using a catch
clause to catch errors or to display them is a good practice.
Permit united states of america test these out. Click the first button that says Native Browser
and information technology should open the link in the device's browser.

The default web browser opens, and it loads the website. There is no WebView
being used, so you do non have to add navigation strategy to handle this. Now, click on the button Text Bulletin
and find information technology should open the default SMS or text service application.

The third object in the links
array is to open up the default E-mail client app. Since there is no electronic mail client app install on iOS simulator, I am going to evidence you lot the demo of running the application on a real Android device.

It works like a charm by opening the Gmail client app on the real device. Now, lastly, let u.s. notice out what happens when you click on the push that says YouTube. It volition piece of work in a like style and open up the video link in the YouTube application.

Conclusion
By now, yous understand how to create a WebView
component or apply the Linking
module in your React Native application. Deep linking is of import in mobile app development, and this tutorial provides yous with an introduction on how to get started and non to get stuck in the beginning.
I hope this tutorial provided y'all an easy walkthrough to grab the bones concepts and build something of your own.
If you like this post, please leave a shoutout for me. I am always available on Twitter or you tin can check the rest of my tutorials hither.
Y'all will find the consummate source code at this Github repository.
Source: https://www.crowdbotics.com/blog/how-to-use-webviews-and-deep-linking-in-react-native-apps
Post a Comment for "An Error Occurred Please Try Again Later Youtube Webview in Simulator"