Create a Youtube-integrated application using React Native

Introduction

Introduction

While building certain types of mobile apps, you might need to have media files displayed in the app. In this tutorial, we will see how to integrate media from YouTube into our mobile apps.

What we'll build

We will build a simple mobile app using React Native called OurTube which will pull videos from the new trailers on Rotten Tomato YouTube channel via the Youtube API and display them to the user. After displaying, we should also be able to tap on a video and have it play inside the app.

Prerequisites

A basic understanding of React and React Native is required for this tutorial.

Getting started

Youtube is a video sharing website and it allows users to upload, rate, like, dislike, comment on videos and a lot more. Youtube also allows users to live stream videos. Youtube is also used widely for video blogging, educational purposes, movies, and trailers, and so on. With the Youtube API, users can find, watch, and manage content on YouTube. It also allows you to add YouTube functionality to your website and mobile apps.

Obtaining your YouTube API key

To get started, the first step is to obtain our developer API key from the developer console. If you prefer a video tutorial, you can find a detailed video tutorial on how to obtain your developer API keys for YouTube here.

After obtaining your API key that should look like AIzaSy****DjoCmWdzH*****cZYjOVg8o******, we require the playlist ID we would like to fetch. To get the playlist ID:

  • Go to Rotten Tomatoes TV channel YouTube page -> New Trailers Playlist
  • Copy the URL from the address bar e.g https://www.youtube.com/playlist?list=PLTovKDoAy18KZ6sUQcmK2RDQeYkm2xUNt and the playlist ID will be the string after the list query in the URL which is PLTovKDoAy18KZ6sUQcmK2RDQeYkm2xUNt

Setting up our React Native project

To get started, follow the official documentation on how to set up your computer for React Native development. If you already have your computer set up, you need to initiate and create the application project.

    $ react-native init OurTube

Once that is completed, we need to compile and build the application to make sure everything is working fine.

1// For ios
2    $ react-native run-ios
3    
4    // For Android
5    $ react-native run-android

Configure routing using react-native-router-flux

React-native-router-flux is a simple navigation API on top of React Navigation and it allows you to declare all application routes in stack and scenes for easy management and configuration. To get started with react-native-router-flux:

    $ npm install react-native-router-flux --save

Go ahead and create a route file and configure all application routing.

    $ touch Route.js

Route.js should be in the root directory of our OurTube App and the contents will look like:

1// Route.js
2    import React, { Component } from 'react';
3    import {Platform} from 'react-native';
4    // import components from react-native-router-flux
5    import {Router, Stack, Scene} from 'react-native-router-flux';
6    // import our screens as components 
7    import Home from './screens/Home';
8    import WatchVideo from './screens/Video';
9    export default class Routes extends Component<{}> {
10      render() {
11        return(
12          <Router>
13              <Stack key="root">
14                <Scene key="home" component={Home} title="Playlist Videos" />
15                <Scene key="watchvideo" component={WatchVideo} title="View Video"/>
16              </Stack>
17          </Router>
18          )
19      }
20    }

The Router is the main routing component while a Stack is a group of Scenes with it's own navigator, so you can have multiple stacks for navigating. A Scene is the basic routing component for the main router and all Scene components require a key prop that must be unique and a key prop is used to call the screen transition and must be unique to all screens. We have created two scenes called home and watchvideo. The scenes will be called as actions in our Home and Video screens. More information can be found in the official documentation of React Native Router Flux. Update App.js file to look like:

1// App.js
2    import React, { Component } from 'react';
3    import {
4      StyleSheet,
5      View,
6      StatusBar,
7    } from 'react-native';
8    import Routes from './Route';
9    export default class App extends Component<{}> {
10      render() {
11        return (
12          <View style={styles.container}>
13            <StatusBar
14              backgroundColor="#fff"
15              barStyle="dark-content"
16            />
17            <Routes/>
18          </View>
19        );
20      }
21    }
22    const styles = StyleSheet.create({
23      container : {
24        flex: 1,
25      }
26    });

Creating UI components

React Native offers inbuilt UI components and we'll be leveraging these inbuilt components. We will make use of components such as the FlatList, Text, and so on. Let's go ahead to create our project directories and files:

1$ mkdir screens && cd screens
2    $ touch Home.js Video.js

``js // screens/Home.js import React, { Component } from 'react'; import { StyleSheet, SafeAreaView, FlatList, Text, TouchableOpacity } from 'react-native'; import {Actions} from 'react-native-router-flux'; const MAX_RESULT = 15; const PLAYLIST_ID = "PLScC8g4bqD47c-qHlsfhGH3j6Bg7jzFy-"; const API_KEY = ""; export default class Home extends Component<{}> {

1home(){
2    Actions.home();
3  }
4  watchVideo(video_url){
5    Actions.watchvideo({video_url: video_url});
6  }
7  componentWillMount() {
8    this.fetchPlaylistData();
9  }
10  fetchPlaylistData = async () => {
11    const response = await fetch(`https://www.googleapis.com/youtube/v3/playlistItems?playlistId=${PLAYLIST_ID}&maxResults=${MAX_RESULT}&part=snippet%2CcontentDetails&key=${API_KEY}`);
12    const json = await response.json();
13    this.setState({ videos: json['items']});
14    console.log(this.state.videos)
15  };
16  constructor(props) {
17    super(props);
18    this.state = {
19      videos: [],
20    }
21  }
22  render() {
23    const videos = this.state.videos;
24    return (
25      <SafeAreaView style={styles.safeArea}>
26            <FlatList
27              data={this.state.videos}
28              keyExtractor={(_, index) => index.toString()}
29              renderItem={
30                ({item}) => 
31                <TouchableOpacity
32                    style={styles.demacate}
33                    onPress={() => this.watchVideo(item.contentDetails.videoId)}
34                >
35                <Text 
36                  style={styles.item} 
37                > 
38                {item.snippet.title} 
39                </Text>
40                </TouchableOpacity>
41              }
42            />
43      </SafeAreaView>
44    );
45  }
46}
47const styles = StyleSheet.create({
48  safeArea: {
49    flex: 1,
50    backgroundColor: '#fff'
51  },
52  demacate: {
53    borderBottomColor: 'blue',
54    borderBottomWidth: 2,
55    borderRadius:10
56  },
57  item: {
58    padding: 10,
59    fontSize: 12,
60    height: 44,
61  },
62});
1The first thing we do in the `Home.js` file is to import all the necessary components to build the home screen. Like the variable names imply, `MAX_RESULT` is the number of videos we want to return from the youtube API, `PLAYLIST_ID` is a string of the youtube playlist we want to fetch and `API_KEY` will hold our Youtube API access key.
2
3The `home()` and `watchVideo()` functions will call navigation actions that allow us to navigate from page to page. The `fetchPlaylistData()` is an asynchronous function that allows us to fetch data from the Youtube API and `componentWillMount()` allows us to fetch the async data after the screen is rendered. 
4
5The response data is converted to JSON and stored in the videos state and will be passed to our component during rendering. 
6
7In the `render()` we define a prop that holds data fetched such as video id from our Youtube API and we pass it to the videos page as a `video_url` prop so we don't have to do a network fetch to get the same data on the next screen. 
8
9Our `render()` function renders the screen and we use the SafeAreaView component to handle the screens of newer devices such as the iPhone X, XR and higher so the screen doesn't overlap. We use the `Flatlist` component to render our data from the `videos` state using the `renderItem` prop.
10
11```js
12    // screens/Video.js
13    import React, { Component } from 'react';
14    import { StyleSheet, SafeAreaView, View, WebView } from 'react-native';
15    import {Actions} from 'react-native-router-flux';
16    export default class WatchVideo extends Component<{}> {
17      
18      home(){
19        Actions.home();
20      }
21      videos(){
22        Actions.videos();
23      }
24      constructor(props) {
25        super(props);
26        console.log(this.props);
27      }
28      render() {
29        return (
30          <SafeAreaView style={styles.safeArea}>
31              { 
32                <WebView
33                  source={{ uri: "https://www.youtube.com/embed/"+this.props.video_url}}
34                  startInLoadingState={true} 
35                />
36              }
37          </SafeAreaView>
38        );
39      }
40    }
41    const styles = StyleSheet.create({
42      safeArea: {
43        flex: 1,
44        backgroundColor: '#fff'
45      }
46    });

In the Video.js file, we also import all the necessary components to build our interface and likewise, create routing actions so we can navigate back to our home screen. In the render() function, the data we stored in the video_url props is accessed and rendered using the Webview video component. The component is customizable and allows us to define the URL source, loaders, and so on.

Building our app

To build and compile our code on iOS:

    $ react-native run-ios

To build and compile our code on Android:

    $ react-native run-android

After build is successful, your application should look like:

  • Home Screen

    react-ative-youtube-1

  • Video Screen

    react-ative-youtube-2

Conclusion

The YouTube API is robust and allows us to watch videos, get video metadata, and so on. The data can be integrated with any mobile development framework and as seen in OurTube app using React Native. OurTube app is in a simple version right now, but you can go ahead to add some more functionalities such as liking and disliking videos, reporting comments, and so on by reading the Google Developer guide for Youtube in order to build complex and robust applications. The codebase to this tutorial is available in a public GitHub repository. Feel free to play around with it.