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 init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli
command line utility. Open the terminal and go to the workspace and run
npm install -g react-native-cli
Run the following commands to create a new React Native project
react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next
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
1 | cd ProjectName |
Run the following command
1 | 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
1 | cd ios && pod install && cd .. |
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 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 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.
Open App.js in any code editor and replace the code with the following code
App.js
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 | /*This is an Example of YouTube integration in React Native*/ import React from 'react'; import { StyleSheet, View, Text, ScrollView, TouchableOpacity, PixelRatio, Dimensions, Platform, } from 'react-native'; import YouTube, { YouTubeStandaloneIOS, YouTubeStandaloneAndroid, } from 'react-native-youtube'; export default class RCTYouTubeExample extends React.Component { state = { isReady: false, status: null, quality: null, error: null, isPlaying: true, isLooping: true, duration: 0, currentTime: 0, fullscreen: false, containerMounted: false, containerWidth: null, }; render() { return ( <ScrollView style={styles.container} onLayout={({ nativeEvent: { layout: { width }, }, }) => { if (!this.state.containerMounted) this.setState({ containerMounted: true }); if (this.state.containerWidth !== width) this.setState({ containerWidth: width }); }}> {this.state.containerMounted && ( <YouTube ref={component => { this._youTubeRef = component; }} // You must have an API Key for the player to load in Android apiKey="YOUR_API_KEY" // Un-comment one of videoId / videoIds / playlist. // You can also edit these props while Hot-Loading in development mode to see how // it affects the loaded native module videoId="ncw4ISEU5ik" // videoIds={['HcXNPI-IPPM', 'XXlZfc1TrD0', 'czcjU1w-c6k', 'uMK0prafzw0']} // playlistId="PLF797E961509B4EB5" play={this.state.isPlaying} loop={this.state.isLooping} fullscreen={this.state.fullscreen} controls={1} style={[ { height: PixelRatio.roundToNearestPixel( this.state.containerWidth / (16 / 9) ), }, styles.player, ]} onError={e => this.setState({ error: e.error })} onReady={e => this.setState({ isReady: true })} onChangeState={e => this.setState({ status: e.state })} onChangeQuality={e => this.setState({ quality: e.quality })} onChangeFullscreen={e => this.setState({ fullscreen: e.isFullscreen }) } onProgress={e => this.setState({ duration: e.duration, currentTime: e.currentTime, }) } /> )} {/* Playing / Looping */} <View style={styles.buttonGroup}> <TouchableOpacity style={styles.button} onPress={() => this.setState(s => ({ isPlaying: !s.isPlaying }))}> <Text style={styles.buttonText}> {this.state.status == 'playing' ? 'Pause' : 'Play'} </Text> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={() => this.setState(s => ({ isLooping: !s.isLooping }))}> <Text style={styles.buttonText}> {this.state.isLooping ? 'Looping' : 'Not Looping'} </Text> </TouchableOpacity> </View> {/* Previous / Next video */} <View style={styles.buttonGroup}> <TouchableOpacity style={styles.button} onPress={() => this._youTubeRef && this._youTubeRef.previousVideo() }> <Text style={styles.buttonText}>Previous Video</Text> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={() => this._youTubeRef && this._youTubeRef.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={() => this._youTubeRef && this._youTubeRef.seekTo(15)}> <Text style={styles.buttonText}>15 Seconds</Text> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={() => this._youTubeRef && this._youTubeRef.seekTo(2 * 60)}> <Text style={styles.buttonText}>2 Minutes</Text> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={() => this._youTubeRef && this._youTubeRef.seekTo(15 * 60) }> <Text style={styles.buttonText}>15 Minutes</Text> </TouchableOpacity> </View> {/* Play specific video in a videoIds array by index */} {this._youTubeRef && this._youTubeRef.props.videoIds && Array.isArray(this._youTubeRef.props.videoIds) && ( <View style={styles.buttonGroup}> {this._youTubeRef.props.videoIds.map((videoId, i) => ( <TouchableOpacity key={i} style={styles.button} onPress={() => this._youTubeRef && this._youTubeRef.playVideoAt(i) }> <Text style={[ styles.buttonText, styles.buttonTextSmall, ]}>{`Video ${i}`}</Text> </TouchableOpacity> ))} </View> )} {/* Get current played video's position index when playing videoIds*/} <View style={styles.buttonGroup}> <TouchableOpacity style={styles.button} onPress={() => this._youTubeRef && this._youTubeRef .videosIndex() .then(index => this.setState({ videosIndex: index })) .catch(errorMessage => this.setState({ error: errorMessage })) }> <Text style={styles.buttonText}> Get Videos Index: {this.state.videosIndex} </Text> </TouchableOpacity> </View> {/* Fullscreen */} {!this.state.fullscreen && ( <View style={styles.buttonGroup}> <TouchableOpacity style={styles.button} onPress={() => this.setState({ fullscreen: true })}> <Text style={styles.buttonText}>Set Fullscreen</Text> </TouchableOpacity> </View> )} {/* Update Progress & Duration (Android) */} {Platform.OS === 'android' && ( <View style={styles.buttonGroup}> <TouchableOpacity style={styles.button} onPress={() => this._youTubeRef ? this._youTubeRef .currentTime() .then(currentTime => this.setState({ currentTime })) .catch(errorMessage => this.setState({ error: errorMessage }) ) : this._youTubeRef .duration() .then(duration => this.setState({ duration })) .catch(errorMessage => this.setState({ error: errorMessage }) ) }> <Text style={styles.buttonText}> Update Progress & Duration (Android) </Text> </TouchableOpacity> </View> )} {/* Standalone Player (iOS) */} {Platform.OS === 'ios' && YouTubeStandaloneIOS && ( <View style={styles.buttonGroup}> <TouchableOpacity style={styles.button} onPress={() => YouTubeStandaloneIOS.playVideo('KVZ-P-ZI6W4') .then(() => console.log('iOS Standalone Player Finished')) .catch(errorMessage => this.setState({ error: errorMessage }) ) }> <Text style={styles.buttonText}>Launch Standalone Player</Text> </TouchableOpacity> </View> )} {/* Standalone Player (Android) */} {Platform.OS === 'android' && YouTubeStandaloneAndroid && ( <View style={styles.buttonGroup}> <TouchableOpacity style={styles.button} onPress={() => YouTubeStandaloneAndroid.playVideo({ apiKey: 'YOUR_API_KEY', videoId: 'KVZ-P-ZI6W4', autoplay: true, lightboxMode: false, startTime: 124.5, }) .then(() => console.log('Android Standalone Player Finished') ) .catch(errorMessage => this.setState({ error: errorMessage }) ) }> <Text style={styles.buttonText}>Standalone: One Video</Text> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={() => YouTubeStandaloneAndroid.playVideos({ apiKey: 'YOUR_API_KEY', videoIds: [ 'HcXNPI-IPPM', 'XXlZfc1TrD0', 'czcjU1w-c6k', 'uMK0prafzw0', ], autoplay: false, lightboxMode: true, startIndex: 1, startTime: 99.5, }) .then(() => console.log('Android Standalone Player Finished') ) .catch(errorMessage => this.setState({ error: errorMessage }) ) }> <Text style={styles.buttonText}>Videos</Text> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={() => YouTubeStandaloneAndroid.playPlaylist({ apiKey: 'YOUR_API_KEY', playlistId: 'PLF797E961509B4EB5', autoplay: false, lightboxMode: false, startIndex: 2, startTime: 100.5, }) .then(() => console.log('Android Standalone Player Finished') ) .catch(errorMessage => this.setState({ error: errorMessage }) ) }> <Text style={styles.buttonText}>Playlist</Text> </TouchableOpacity> </View> )} {/* Reload iFrame for updated props (Only needed for iOS) */} {Platform.OS === 'ios' && ( <View style={styles.buttonGroup}> <TouchableOpacity style={styles.button} onPress={() => this._youTubeRef && this._youTubeRef.reloadIframe() }> <Text style={styles.buttonText}>Reload iFrame (iOS)</Text> </TouchableOpacity> </View> )} <Text style={styles.instructions}> {this.state.isReady ? 'Player is ready' : 'Player setting up...'} </Text> <Text style={styles.instructions}>Status: {this.state.status}</Text> <Text style={styles.instructions}>Quality: {this.state.quality}</Text> {/* Show Progress */} <Text style={styles.instructions}> Progress: {Math.trunc(this.state.currentTime)}s ({Math.trunc( this.state.duration / 60 )}:{Math.trunc(this.state.duration % 60)}s) {Platform.OS !== 'ios' && ( <Text> (Click Update Progress & Duration)</Text> )} </Text> <Text style={styles.instructions}> {this.state.error ? 'Error: ' + this.state.error : ''} </Text> </ScrollView> ); } } const styles = StyleSheet.create({ container: { backgroundColor: 'white', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, 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
To run the project on an Android Virtual Device or on real debugging devicereact-native run-android
or on the iOS Simulator by runningreact-native run-ios
(macOS only).
This is how you can integrate Youtube video in your React Native Application. If you have any doubt 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. 🙂
It is so good example, But It not working if not set fullscreen=true when I define in a screen on createStackNavigator.
I am not clear with that can you please elaborate more?
i have more than one video…and also all have different videoId. but all this video take same id in flatlist? why
It must be the problem of your code. Can you please share the code on aboutreact11@gmail.com