DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Build a React Native Chat App for Android
  • Optimizing User Experience in React Native
  • A Guide To Eliminate Common Performance Issues in React Native App Development
  • Navigation in a React Native Web Application

Trending

  • Rethinking Recruitment: A Journey Through Hiring Practices
  • Segmentation Violation and How Rust Helps Overcome It
  • Chaos Engineering for Microservices
  • Unlocking AI Coding Assistants Part 1: Real-World Use Cases
  1. DZone
  2. Coding
  3. JavaScript
  4. How To Embed YouTube Videos in React Native

How To Embed YouTube Videos in React Native

In this article, we are going to describe how to add a video player to your React Native app in order to support the integration and playing of Youtube videos.

By 
krissanawatt kaewsanmunag user avatar
krissanawatt kaewsanmunag
·
Mar. 11, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
27.6K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

In this article, we are going to describe how to add a video player in your React Native app in order to support playing Youtube videos. The use of video is the present and the future of the internet, as you can already see through apps such as TikTok, Youtube, Instagram or Facebook.

Video support is a feature that makes your app more lively, more interactive, and more fun. By the end of this article, you will be able to embed any Youtube videos of your choice in React Native apps easily. For you to understand this tutorial, you should be familiar with the use of useRef and useState in React Native.

To achieve playing Youtube videos in React Native, we will be making use of the npm dependency named react-native-youtube-iframe. We will work through using this library by fully integrating it into an app.

Installation

You need to install react-native-webview first. Simply run:

Shell
 




x


 
1
yarn add react-native-webview
2

          
3
#or
4

          
5
npm install react-native-webview


then install react-native-youtube-iframe:

Shell
 




xxxxxxxxxx
1


 
1
yarn add react-native-youtube-iframe
2

          
3
#or 
4

          
5
npm install react-native-youtube-iframe


Usage

The required props here are height and the videoId of the Youtube video you intend to play in the React Native app and as seen in the app below, we have a Casey Neistat travel vlog on display:

JavaScript
 




xxxxxxxxxx
1
24


 
1
/**
2
 * Sample React Native App
3
 * https://github.com/facebook/react-native
4
 *
5
 * @format
6
 * @flow strict-local
7
 */
8

          
9
import React from 'react';
10
import {View} from 'react-native';
11
import YoutubePlayer from 'react-native-youtube-iframe';
12

          
13
const App = () => {
14

          
15
  return (
16
    <View>
17
      <YoutubePlayer
18
        height={300}
19
        play={true}
20
        videoId={'84WIaK3bl_s'}
21
      />
22
    </View>
23
  );
24
};



The play prop is set to true, so let us take it a step further and control play and pause actions:

JavaScript
 




xxxxxxxxxx
1
30


 
1
/**
2
 * Sample React Native App
3
 * https://github.com/facebook/react-native
4
 *
5
 * @format
6
 * @flow strict-local
7
 */
8

          
9
import React, {useState, useCallback} from 'react';
10
import {Button, View, Alert} from 'react-native';
11
import YoutubePlayer from 'react-native-youtube-iframe';
12

          
13
const App = () => {
14
  const [playing, setPlaying] = useState(false);
15

          
16
  const togglePlaying = () => {
17
    setPlaying((prev) => !prev);
18
  }
19

          
20
  return (
21
    <View>
22
      <YoutubePlayer
23
        height={300}
24
        play={playing}
25
        videoId={'84WIaK3bl_s'}
26
      />
27
      <Button title={playing ? 'pause' : 'play'} onPress={togglePlaying} />
28
    </View>
29
  );
30
};



Now we have a control to play and pause the Youtube video. It would be nice to add a feature to tell the user that the video is done playing by passing a callback such as the onChangeState prop provided by the dependency:

Java
 




xxxxxxxxxx
1
38


 
1
/**
2
 * Sample React Native App
3
 * https://github.com/facebook/react-native
4
 *
5
 * @format
6
 * @flow strict-local
7
 */
8

          
9
import React, {useState} from 'react';
10
import {Button, View, Alert} from 'react-native';
11
import YoutubePlayer from 'react-native-youtube-iframe';
12

          
13
const App = () => {
14
  const [playing, setPlaying] = useState(false);
15

          
16
  const onStateChange = (state) => {
17
    if (state === 'ended') {
18
      setPlaying(false);
19
      Alert.alert('video has finished playing!');
20
    }
21
  }
22

          
23
  const togglePlaying = () => {
24
    setPlaying((prev) => !prev);
25
  }
26

          
27
  return (
28
    <View>
29
      <YoutubePlayer
30
        height={300}
31
        play={playing}
32
        videoId={'84WIaK3bl_s'}
33
        onChangeState={onStateChange}
34
      />
35
      <Button title={playing ? 'pause' : 'play'} onPress={togglePlaying} />
36
    </View>
37
  );
38
};



Now that we’re done learning the basic usage of this Youtube player dependency, let us go ahead and build a complete control for our video player to play, pause, skip, and mute.

JavaScript
 




xxxxxxxxxx
1
81


 
1
import React, {useState, useRef} from 'react';
2
import {View, Alert, StyleSheet} from 'react-native';
3
import YoutubePlayer from 'react-native-youtube-iframe';
4
import {Icon} from 'react-native-elements';
5

          
6
const App = () => {
7
  const [playing, setPlaying] = useState(false);
8
  const [isMute, setMute] = useState(false);
9
  const controlRef = useRef();
10

          
11
  const onStateChange = (state) => {
12
    if (state === 'ended') {
13
      setPlaying(false);
14
      Alert.alert('video has finished playing!');
15
    }
16
    if (state !== 'playing') {
17
      setPlaying(false);
18
    }
19
  };
20

          
21
  const togglePlaying = () => {
22
    setPlaying((prev) => !prev);
23
  };
24

          
25
  const seekBackAndForth = (control) => {
26
    console.log('currentTime');
27
    controlRef.current?.getCurrentTime().then((currentTime) => {
28
      control === 'forward'
29
        ? controlRef.current?.seekTo(currentTime + 15, true)
30
        : controlRef.current?.seekTo(currentTime - 15, true);
31
    });
32
  };
33

          
34
  const muteVideo = () => setMute(!isMute);
35

          
36
  const ControlIcon = ({name, onPress}) => (
37
    <Icon onPress={onPress} name={name} size={40} color="#fff" />
38
  );
39

          
40
  return (
41
    <View style={styles.container}>
42
      <YoutubePlayer
43
        height={300}
44
        ref={controlRef}
45
        play={playing}
46
        mute={isMute}
47
        videoId={'84WIaK3bl_s'}
48
        onChangeState={onStateChange}
49
      />
50
      <View style={styles.controlContainer}>
51
        <ControlIcon
52
          onPress={() => seekBackAndForth('rewind')}
53
          name="skip-previous"
54
        />
55
        <ControlIcon
56
          onPress={togglePlaying}
57
          name={playing ? 'pause' : 'play-arrow'}
58
        />
59
        <ControlIcon
60
          onPress={() => seekBackAndForth('forward')}
61
          name="skip-next"
62
        />
63
      </View>
64
      <ControlIcon
65
        onPress={muteVideo}
66
        name={isMute ? 'volume-up' : 'volume-off'}
67
      />
68
    </View>
69
  );
70
};
71

          
72
const styles = StyleSheet.create({
73
  container: {
74
    flex: 1,
75
    backgroundColor: 'darkblue',
76
  },
77
  controlContainer: {
78
    flexDirection: 'row',
79
    justifyContent: 'space-around',
80
  },
81
});



We have added more custom controls to the original component we already had before and added callbacks to seek forward and backward using the playerRef ref. The mute control is basically managed by the isMute state but it is worthy of note that the dependency provides a method isMuted (returns a promise that resolves to true if the video is muted, false if not) to determine if the video is muted or not.

Conclusion

Embedding and playing Youtube videos in your React Native app is seamless and a more affordable way of displaying videos in your app, given that Youtube will support the costs of hosting the video itself. The npm dependency we described is really easy to use and is highly customizable as we have seen in the above snippet where we added forward and rewind controls.

Next time you’re looking to add Youtube video support to React Native apps, refer to this tutorial. If you enjoyed the project, please consider sharing the link with your friends and community. Cheers!

React Native React (JavaScript library) app

Published at DZone with permission of krissanawatt kaewsanmunag. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Build a React Native Chat App for Android
  • Optimizing User Experience in React Native
  • A Guide To Eliminate Common Performance Issues in React Native App Development
  • Navigation in a React Native Web Application

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!