Lazy Approach to Display YouTube Videos in A React Native App

mutatedbread

Ng Chen Hon

Posted on November 17, 2017

Lazy Approach to Display YouTube Videos in A React Native App

Sometimes ago, I made an half-baked RN app for an internship job. I would need to display company videos from their YouTube account. Went I was to find plugins on npm. As I did not come across a working plugin at that moment so I decided to go with the laziest method I thought of.

WEBVIEW FTW !!!

Yass, I am lazy to write a native plugin so there is WebView :)

<WebView 
    ref={(ref) => { this.videoPlayer = ref;}}
    scalesPageToFit={true} 
    source={{ html: '<html><meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" /><iframe src="https://www.youtube.com/embed/' + this.props.navigation.state.params.videoId + '?modestbranding=1&playsinline=1&showinfo=0&rel=0" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe></html>'}} 
    onShouldStartLoadWithRequest={this.onShouldStartLoadWithRequest} //for iOS
    onNavigationStateChange ={this.onShouldStartLoadWithRequest} //for Android
/>
Enter fullscreen mode Exit fullscreen mode
  1. It has a this.videoPlayer component reference.
  2. this.props.navigation.state.params.videoId is a parameter pass in by Redux using React Navigation NavigationActions.navigate.
  3. It has a source to an embed YouTube player with 100% css height and width.

Then, there is a Youtube logo on the bottom which the user can tap to either open the native YouTube app or a new tab in their default browsers to YouTube.

I did not want the user to leave the app as well. I included a little "hack" that disallow this action.

onShouldStartLoadWithRequest = (navigator) => {
    if (navigator.url.indexOf('embed') !== -1
    ) {
        return true;
    } else {
        this.videoPlayer.stopLoading(); //Some reference to your WebView to make it stop loading that URL
        return false;
    }    
}
Enter fullscreen mode Exit fullscreen mode

For every url change, the WebView will call the function delivered to its onShouldStartLoadWithRequest and onNavigationStateChange props. It simply check if the embed from YouTube web embed url is still there or not.

Otherwise, the WebView will stop loading.


Quick and dirty. Ugly but IT WORKS

šŸ’– šŸ’Ŗ šŸ™… šŸš©
mutatedbread
Ng Chen Hon

Posted on November 17, 2017

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related