YouTube Video Integration
Here is an example of YouTube Video Integration in React Native. To integrate the YouTube video in our example we will use a library called react-native-youtube
. Which provides a YouTube component which is very easy to use.
To Make a React Native App
Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
This will make a project structure with an index file named App.js in your project directory.
Installation of Dependency
To use YouTube
we need to install react-native-youtube
package. To install this
Open the terminal and jump into your project
cd ProjectName
Run the following command
npm install react-native-youtube --save
This command will copy all the dependencies into your node_module directory.
CocoaPods Installation
After the updation of React Native 0.60, they have introduced autolinking so we do not require to link the library but need to install pods. So to install pods use
cd ios && pod install && cd ..
How to Generate the API Key?
To use Youtube in your Application we have to get Youtube API key from the Google Developer console. For that, open the Developer console and log in from your Google account.
If you have already created any project you can use that or you can create a new one like this
After creating the project you can see all of your created project a drop-down in the top left corner. Now select the project from the dropdown and goto to the credential section.
You can find the create credential option there.
Hit on the create credential button and it will create an API key to the user in your YouTube Application
Before we add this API key in our project you have to enable the API Library/ Feature which you want to use in your project. For that, you can search for the Youtube and you will find the Youtube related API Library. We will enable the YouTube Data API. Click on YouTube Data API and you will found the enable button to enable the YouTube Data API.
Now after enabling the API key, we have to add this API key in our project’s App.js file. Just replace YOUR_API_KEY everywhere with your generated API key.
Code
Open App.js in any code editor and replace the code with the following code
App.js
// Example of YouTube Video Integration in React Native
// https://aboutreact.com/youtube-video-integration-in-react-native/
// Import React
import React, {useState, useRef} from 'react';
// Import required components
import {
SafeAreaView,
StyleSheet,
View,
Text,
ScrollView,
TouchableOpacity,
PixelRatio,
} from 'react-native';
// Import Youtube Players
import YouTube from 'react-native-youtube';
const App = () => {
const youtubePlayerRef = useRef();
const singleVideoId = '4A426Yjm_jM';
const listVideoIds = [
'4A426Yjm_jM',
'BfmIgt_kPvM',
'F9LwbmIWIr0'
];
const [isReady, setIsReady] = useState(false);
const [status, setStatus] = useState(null);
const [quality, setQuality] = useState(null);
const [error, setError] = useState(null);
const [isPlaying, setIsPlaying] = useState(true);
const [isLooping, setIsLooping] = useState(true);
const [duration, setDuration] = useState(0);
const [currentTime, setCurrentTime] = useState(0);
const [fullscreen, setFullscreen] = useState(false);
const [containerMounted, setContainerMounted] = useState(false);
const [containerWidth, setContainerWidth] = useState(null);
return (
<SafeAreaView style={{flex: 1}}>
<ScrollView
style={styles.container}
onLayout={({
nativeEvent: {
layout: {width},
},
}) => {
if (!containerMounted) setContainerMounted(true);
if (containerWidth !== width) setContainerWidth(width);
}}>
{containerMounted && (
<YouTube
ref={youtubePlayerRef}
// You must have an API Key
apiKey="Replace Your API Key"
// Un-comment one of videoId / videoIds / playlist.
// videoId={singleVideoId}
videoIds={listVideoIds}
// playlistId="PLF797E961509B4EB5"
play={isPlaying}
loop={isLooping}
fullscreen={fullscreen}
controls={1}
style={[
{
height: PixelRatio.roundToNearestPixel(
containerWidth / (16 / 9),
),
},
styles.player,
]}
onError={(e) => setError(e.error)}
onReady={(e) => setIsReady(true)}
onChangeState={(e) => setStatus(e.state)}
onChangeQuality={(e) => setQuality(e.quality)}
onChangeFullscreen={(e) => setFullscreen(e.isFullscreen)}
onProgress={(e) => {
setDuration(e.duration);
setCurrentTime(e.currentTime);
}}
/>
)}
<Text style={styles.titleText}>
Example of YouTube Video Integration in React Native
</Text>
{/* Playing / Looping */}
<View style={styles.buttonGroup}>
<TouchableOpacity
style={styles.button}
onPress={() => setIsPlaying((isPlaying) => !isPlaying)}>
<Text style={styles.buttonText}>
{status == 'playing' ? 'Pause' : 'Play'}
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => setIsLooping((isLooping) => !isLooping)}>
<Text style={styles.buttonText}>
{isLooping ? 'Looping' : 'Not Looping'}
</Text>
</TouchableOpacity>
</View>
{/* Previous / Next video */}
<View style={styles.buttonGroup}>
<TouchableOpacity
style={styles.button}
onPress={() =>
youtubePlayerRef.current &&
youtubePlayerRef.current.previousVideo()
}>
<Text style={styles.buttonText}>Previous Video</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() =>
youtubePlayerRef.current &&
youtubePlayerRef.current.nextVideo()
}>
<Text style={styles.buttonText}>Next Video</Text>
</TouchableOpacity>
</View>
{/* Go To Specific time in played video with seekTo() */}
<View style={styles.buttonGroup}>
<TouchableOpacity
style={styles.button}
onPress={() =>
youtubePlayerRef.current &&
youtubePlayerRef.current.seekTo(15)
}>
<Text style={styles.buttonText}>15 Seconds</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() =>
youtubePlayerRef.current &&
youtubePlayerRef.current.seekTo(2 * 60)
}>
<Text style={styles.buttonText}>2 Minutes</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() =>
youtubePlayerRef.current &&
youtubePlayerRef.current.seekTo(15 * 60)
}>
<Text style={styles.buttonText}>15 Minutes</Text>
</TouchableOpacity>
</View>
{/* Play specific video in a videoIds array by index */}
{youtubePlayerRef.current &&
youtubePlayerRef.current.props.videoIds &&
Array.isArray(youtubePlayerRef.current.props.videoIds) && (
<View style={styles.buttonGroup}>
{youtubePlayerRef.current.props.videoIds.map(
(videoId, i) => (
<TouchableOpacity
key={i}
style={styles.button}
onPress={() =>
youtubePlayerRef.current &&
youtubePlayerRef.current.playVideoAt(i)
}>
<Text
style={[
styles.buttonText,
styles.buttonTextSmall,
]}>{`Video ${i}`}</Text>
</TouchableOpacity>
)
)}
</View>
)}
{/* Fullscreen */}
{!fullscreen && (
<View style={styles.buttonGroup}>
<TouchableOpacity
style={styles.button}
onPress={() => setFullscreen(true)}>
<Text style={styles.buttonText}>Set Fullscreen</Text>
</TouchableOpacity>
</View>
)}
<Text style={styles.instructions}>
{isReady ? 'Player is ready' : 'Player setting up...'}
</Text>
<Text style={styles.instructions}>Status: {status}</Text>
<Text style={styles.instructions}>Quality: {quality}</Text>
{/* Show Progress */}
<Text style={styles.instructions}>
Progress:
{Math.trunc(currentTime)}s
({Math.trunc(duration / 60)}:
{Math.trunc(duration % 60)}s)
</Text>
<Text style={styles.instructions}>
{error ? 'Error: ' + error : ''}
</Text>
</ScrollView>
</SafeAreaView>
);
};
export default App;
const styles = StyleSheet.create({
container: {
backgroundColor: 'white',
},
titleText: {
fontSize: 22,
fontWeight: 'bold',
textAlign: 'center',
paddingVertical: 20,
},
buttonGroup: {
flexDirection: 'row',
alignSelf: 'center',
},
button: {
paddingVertical: 4,
paddingHorizontal: 8,
alignSelf: 'center',
},
buttonText: {
fontSize: 18,
color: 'blue',
},
buttonTextSmall: {
fontSize: 15,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
player: {
alignSelf: 'stretch',
marginVertical: 10,
},
});
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshots
This is how you can integrate Youtube video in your React Native Application. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!
Hope you liked it. 🙂
As always, superb examples, thanks!
How to download youtube video for offline support within my application?
Can anyone help?
Hi Team,
Is it possible to play private youtube videos in react native?
Thanks
I don’t think so. You can see this
while moving between tabs app crashes without any error.