Example of YouTube Video Integration in React Native

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 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

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

/*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 device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

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. 🙂


Related Posts

10 thoughts on “Example of YouTube Video Integration in React Native”

  1. This is a very nice, I have faced a problem of playing a youtube video, it was failed all the time after the initial loading, I need to play continuously without interruption, Fullscreen and all other functions were worked well.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.