Lazy Approach to Display YouTube Videos in A React Native App
Ng Chen Hon
Posted on November 17, 2017
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
/>
- It has a
this.videoPlayer
component reference. -
this.props.navigation.state.params.videoId
is a parameter pass in by Redux using React NavigationNavigationActions.navigate
. - 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;
}
}
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
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
November 29, 2024
November 29, 2024
November 28, 2024