YouTube is one of the biggest online free video hosting platform provided by Google on internet. YouTube gives us the free facility to Embed YouTube Video in web application like Websites and mobile applications like iOS mobile apps, Android mobile apps, Windows mobile apps. So in this tutorial we would going to create a react native app to Embed YouTube Video in both Android and iOS applications using WebView component. So let’s get started .
Contents in this project Embed YouTube Video in React Native Android iOS App :
1. Copy the YouTube video URL from web browser address bar.
2. Now we need to replace the
watch?v= with
embed text.
For example : The video URL i am using in this tutorial is :
https://youtube.com/watch?v=dFKhWe2bBkM now i am replacing the
watch?v= with
embed . After replacing the text the video URL should look like this :
https://youtube.com/embed/dFKhWe2bBkM . This would be your embed URL.
3. Import StyleSheet, View, WebView and Platform component in your project.
1
2
3
|
import React, { Component } from ‘react’;
import { StyleSheet, View, WebView, Platform } from ‘react-native’;
|
4. Create a Root View in render’s return block with 300 pixels height.
1
2
3
4
5
6
7
8
9
10
|
render() {
return (
<View style={{ height: 300 }}>
</View>
);
}
|
5. Now we would create the WebView component in View and set the embed URL as source.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
render() {
return (
<View style={{ height: 300 }}>
<WebView
style={ styles.WebViewContainer }
javaScriptEnabled={true}
domStorageEnabled={true}
source={{uri: ‘https://youtube.com/embed/dFKhWe2bBkM’ }}
/>
</View>
);
}
|
6. Create Style for WebView.
1
2
3
4
5
6
7
8
9
|
const styles = StyleSheet.create({
WebViewContainer: {
marginTop: (Platform.OS == ‘ios’) ? 20 : 0,
}
});
|
7. Complete source code for App.js File :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
import React, { Component } from ‘react’;
import { StyleSheet, View, WebView, Platform } from ‘react-native’;
export default class App extends Component<{}> {
render() {
return (
<View style={{ height: 300 }}>
<WebView
style={ styles.WebViewContainer }
javaScriptEnabled={true}
domStorageEnabled={true}
source={{uri: ‘https://youtube.com/embed/dFKhWe2bBkM’ }}
/>
</View>
);
}
}
const styles = StyleSheet.create({
WebViewContainer: {
marginTop: (Platform.OS == ‘ios’) ? 20 : 0,
}
});
|
Screenshot in Android device: