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 <a href="https://www.youtube.com/playlist?list=PLTovKDoAy18KZ6sUQcmK2RDQeYkm2xUNt" target="_blank">https://www.youtube.com/playlist?list=PLTovKDoAy18KZ6sUQcmK2RDQeYkm2xUNt</a> 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.

    // For ios
    $ react-native run-ios

    // For Android
    $ 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:

    // Route.js
    import React, { Component } from 'react';
    import {Platform} from 'react-native';
    // import components from react-native-router-flux
    import {Router, Stack, Scene} from 'react-native-router-flux';
    // import our screens as components 
    import Home from './screens/Home';
    import WatchVideo from './screens/Video';
    export default class Routes extends Component<{}> {
      render() {
        return(
          <Router>
              <Stack key="root">
                <Scene key="home" component={Home} title="Playlist Videos" />
                <Scene key="watchvideo" component={WatchVideo} title="View Video"/>
              </Stack>
          </Router>
          )
      }
    }

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:

    // App.js
    import React, { Component } from 'react';
    import {
      StyleSheet,
      View,
      StatusBar,
    } from 'react-native';
    import Routes from './Route';
    export default class App extends Component<{}> {
      render() {
        return (
          <View style={styles.container}>
            <StatusBar
              backgroundColor="#fff"
              barStyle="dark-content"
            />
            <Routes/>
          </View>
        );
      }
    }
    const styles = StyleSheet.create({
      container : {
        flex: 1,
      }
    }); 

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:

    $ mkdir screens && cd screens
    $ 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<{}> {

  home(){
    Actions.home();
  }
  watchVideo(video_url){
    Actions.watchvideo({video_url: video_url});
  }
  componentWillMount() {
    this.fetchPlaylistData();
  }
  fetchPlaylistData = async () => {
    const response = await fetch(`https://www.googleapis.com/youtube/v3/playlistItems?playlistId=${PLAYLIST_ID}&maxResults=${MAX_RESULT}&part=snippet%2CcontentDetails&key=${API_KEY}`);
    const json = await response.json();
    this.setState({ videos: json['items']});
    console.log(this.state.videos)
  };
  constructor(props) {
    super(props);
    this.state = {
      videos: [],
    }
  }
  render() {
    const videos = this.state.videos;
    return (
      <SafeAreaView style={styles.safeArea}>
            <FlatList
              data={this.state.videos}
              keyExtractor={(_, index) => index.toString()}
              renderItem={
                ({item}) => 
                <TouchableOpacity
                    style={styles.demacate}
                    onPress={() => this.watchVideo(item.contentDetails.videoId)}
                >
                <Text 
                  style={styles.item} 
                > 
                {item.snippet.title} 
                </Text>
                </TouchableOpacity>
              }
            />
      </SafeAreaView>
    );
  }
}
const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#fff'
  },
  demacate: {
    borderBottomColor: 'blue',
    borderBottomWidth: 2,
    borderRadius:10
  },
  item: {
    padding: 10,
    fontSize: 12,
    height: 44,
  },
});

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

The `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. 

The response data is converted to JSON and stored in the videos state and will be passed to our component during rendering. 

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

Our `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.

```js
    // screens/Video.js
    import React, { Component } from 'react';
    import { StyleSheet, SafeAreaView, View, WebView } from 'react-native';
    import {Actions} from 'react-native-router-flux';
    export default class WatchVideo extends Component<{}> {

      home(){
        Actions.home();
      }
      videos(){
        Actions.videos();
      }
      constructor(props) {
        super(props);
        console.log(this.props);
      }
      render() {
        return (
          <SafeAreaView style={styles.safeArea}>
              { 
                <WebView
                  source={{ uri: "https://www.youtube.com/embed/"+this.props.video_url}}
                  startInLoadingState={true} 
                />
              }
          </SafeAreaView>
        );
      }
    }
    const styles = StyleSheet.create({
      safeArea: {
        flex: 1,
        backgroundColor: '#fff'
      }
    });

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
  • Video Screen

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.

Thanks for reading ❤

#ios #javascript #reactjs #react-native

Create a Youtube-integrated application using React Native
31.05 GEEK