Building a YouTube Component Using the React-Native WebView | by Daniel Friyia | Mar, 2022

Add YouTube Participant performance to your React-Native App

Not too long ago, I used to be engaged on an app that required entry to YouTube movies. To my shock, there wasn’t a lot in the way in which of fine libraries on NPM. After taking a deep dive on YouTube and React-Native improvement, I noticed that YouTube needs you to simply use their embed.

This posed an attention-grabbing downside.

If we had been working in browser-based JavaScript, it will be trivial to simply copy and paste the JS from the YouTube documentation. When engaged on cellular although, we don’t have the identical luxurious. Fortunately, the WebView in React-Native offers a strong API that permits us to speak between cellular and the WebView’s browser.

On this weblog, I’ll be explaining how we are able to make the most of that API to create a YouTube part we are able to management from React-Native. As at all times, in the event you get caught at any level, try the whole mission repo here.

As we speak, we’ll be constructing this easy app that performs movies via the YouTube embed. You’ll learn to show movies in addition to the best way to talk between the WebView’s JavaScript and React-Native.

The very first thing you’ll need to do is generate an empty TypeScript mission utilizing this command:

npx react-native init YoutubePlayer --template react-native-template-typescript

After producing the mission, run the next command to put in the react-native-webview:

npm i react-native-webview

End up by putting in the brand new Cocoapods in your mission.

cd ios && npx pod set up

When utilizing a posh net part just like the YouTube participant, we are able to’t simply pop in a URL and watch the WebView work. With the intention to assist such a feature-rich part, we have to use the YouTube embed.

I like to recommend beginning by making a file known as iFrame.tsx beneath your src listing. After creating this file, we are able to begin by making a perform known as buildIFrame. This perform will construct the embed a part of our HTML code.

Begin by including a participant div that we are able to use as a goal for the embed.

const buildIFrame = (videoId: string) => `
<div id="participant"></div>

Subsequent, we’ll need to construct the script that makes the YouTube participant seem. We begin by loading the iFrame participant code asynchronously.

...
var tag = doc.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = doc.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
...

At this level, we have to create the YouTube participant and goal the participant div we created. We do that as follows:

The videoId will likely be handed in a bit later, however for now, you may get the display width from the React Native dimensions like this.

import Dimensions from 'react-native';
const width = Dimensions.get('window');

Your buildIFrame perform thus far needs to be as follows.

The subsequent step is to type our iFrame. Take note the kinds for this are fairly particular. It is because we would like the iFrame to fill its father or mother view.

Lastly, let’s create a way that takes in a videoId from YouTube and makes use of it to construct your entire iFrame HTML web page.

Now that we have now the markup we’d like, let’s create the WebView Element. Navigate again to your App.tsx file. At this level, you need to import the WebView part and use it together with the buildHTML perform we simply completed creating. Altogether, the file ought to seem like this:

At this level, it is best to be capable to watch the video in the event you faucet on it.

To create the controls we’re going to add extra code to the buildIFrame perform from earlier. On the internet, the YouTube participant provides you entry to a number of functionalities. Those we use on this mission are enjoying and pausing the video, searching for to a time, and getting the present time within the video.

We wrap these functionalities in JavaScript browser features so we are able to name them from React-Native afterward. After doing this, your buildIFrame will take this manner.

Again within the App.tsx file, we have now the trivial activity of wrapping these features in React-Native features in order that we are able to name them within the browser. Begin by grabbing a ref to the WebView.

const webRef = useRef<WebView>(null);
...
<WebView
ref=webRef

After that, you may name no matter JavaScript features you need on the WebView. Listed here are those we’ll use for this mission:

const playVideo = () => 
webRef.present?.injectJavaScript('play()');
;
const pauseVideo = () =>
webRef.present?.injectJavaScript('pause()');
;
const restartVideo = () =>
webRef.present?.injectJavaScript('seekTo(0)');
;

If we throw in just a few buttons and a few mild styling, our part results in its penultimate kind.

We’re virtually there! At this level, it is best to be capable to play the video with the controls.

The very last thing we’ll need to do is show the timer. To do that, we’ll must put up messages from the WebView and ship them to React-Native each second or so.

We are able to add this performance to our WebView utilizing the postMessage perform. You’ll be able to add this snippet to your iFrame.ts.

setInterval(() => 
const information =
currentDuration: getCurrentTime()

window.ReactNativeWebView.postMessage(JSON.stringify(information));
, 1000)

The perform ought to now comprise the set interval, proven under:

We are able to end up by grabbing these occasions from the WebView and displaying them utilizing a state. Your remaining App.tsx will seem like this:

Your remaining consequence needs to be this:

Video playing with a play, pause, restart, and timer under it.

With YouTube being the first internet hosting service on the web, it’s actually necessary to have the ability to use it in our apps. Above, I gave you the fundamentals for the best way to add it to your app.

Be at liberty to type the controls as you see match in an effort to fit your consumer expertise!

More Posts