YouTube Video in React-Native
Here is an example of YouTube video integration in React Native without an external library.
First, we need to use WebView
we can import it from react-native
(but they recommended over to react-native-webview)
import { WebView } from ‘react-native’;
// or
import { WebView } from ‘react-native-webview’;
We’ll place the code where we want to put the video
videoLink = “https://www.youtube.com/watch?v=RgKKgzVhMgY"
<WebView
javaScriptEnabled={true}
source={{ uri: createEmbedYoutubeUrl(videoLink) }}
style={styles.youtubeVideo} />
The style can look like
youtubeVideo: : {
flex: 0,
marginHorizontal: 8,
backgroundColor: '#000'
}
Now we need to handle createEmbedYoutubeUrl
function
export const createEmbedYoutubeUrl = (youtubeUrl) => {
const youtubeVideoId = getYoutubeVideoId(youtubeUrl)
return `https://www.youtube.com/embed/${youtubeVideoId}? modestbranding=1`
}
We can get the Youtube video id with the help of the regex in the function getYoutubeVideoId
export const getYoutubeVideoId = (url) => {
const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/; const match = url.match(regExp);
return match && match[2].length == 11 ? match[2] : 'error'
}
There are a lot of parameters in the embedded player,
In the example above we set modestbranding=1
to prevent the YouTube logo from displaying in the control bar.
You can find more useful parameters such asautoplay
, loop
, controls
and the time you want the video to start
.
For the full documentation about the embedded player parameters browse the link — https://developers.google.com/youtube/player_parameters