Play YouTube Videos without YouTube API (No API Key) in React Native

Tiempo de lectura: 2 minutos

Reading time: 2 minutes

I’m going to show you how we can play YouTube videos without using the YouTube library for React Native. This way, you won’t have to add an API Key to play videos.

First of all, we need to create a Screen with a WebView.

To do this, we first install WebView:

npm install react-native-webview --save

Once installed, we create our Screen:

import React, { useState } from "react";
import { View, StyleSheet} from "react-native";
import { WebView } from 'react-native-webview';


//Button component
const VideoWebView = ({route}) => {

     const { id_video_youtube } = route.params;

    var urlYoutube = 'https://www.youtube.com/watch?v=' + id_video_youtube;

    return (
        <View style={styles.contenedorInicio}>
            <View style={styles.contenedorVideo}>
                <WebView style={[styles.webview]} source={{ uri: urlYoutube }} />
            </View>
        </View>
    )
};
export default VideoWebView;

const styles = StyleSheet.create({
    contenedorInicio: {
        flex: 1,
        alignContent: 'center',
        alignItems: 'center',
    },
    webview: {
        width: Dimensions.get('window').width,
        height: Dimensions.get('window').height,
        flex: 1,
    },
    contenedorVideo: {
        flex: 10,
        width: '100%',
        height: '100%',
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
});

With this code, we have created our WebView that also adjusts to full screen (Adjust WebView width: 100% in React Native).

To play YouTube videos, we use the id_video_youtube, which is usually in this format: DDJnOPkaAK7

It is concatenated to the URL: https://www.youtube.com/watch?v=

This way, it can be played directly on YouTube.

If we want only the video to appear on the screen, we change the URL to this:

var urlYoutube = "https://www.youtube.com/embed/" + id_video_youtube;

This way, the video appears occupying the entire screen.

If we want to allow full-screen and video controls on Android/iOS, we need to add the following to the WebView:

<WebView style={[styles.webview]}  allowsFullscreenVideo={true} allowsInlineMediaPlayback={true} source={{ uri: urlYoutube }} />

We add allowsFullScreenVideo and allowsInlineMediaPlayback, both set to true, to allow fullscreen. You can find this in the official documentation (https://github.com/react-native-webview/react-native-webview/blob/master/docs/Reference.md#allowsfullscreenvideo)

Leave a Comment