Lorenz Weiß Hi, I'm Lorenz, a frontend-focused web developer. I'm in love with the internet and its people and interested in everything related to it.

Adding videos to React Native with react-native-video

4 min read 1394

Adding Videos To React Native With React-Native-Video

React Native is probably the most widely used hybrid app framework today because it enables developers to create native apps by writing React code, which provides a similar developer experience between websites and apps. Creating apps has never been easier.

But does that mean you can turn your website into an app directly by copying all of your React code into the React Native app? No, unfortunately, it’s not that simple. Even though the code of a React Native app looks similar to the code of a web app written in React, there are some small but critical differences.

Compared to websites and browsers, mobile apps have many native interfaces and functionalities. While React Native apps are compiled to native apps for iOS or Android, some implementations of simple elements differ from what we see in the web version of React. For example, <div> becomes <view>, <p> becomes <text>, and so on.

This makes React Native different from all Cordova-based hybrid app frameworks. But what sounds like a major drawback actually makes it possible for the app to compile to native code instead of to a simulated web view.

One element that is different from native web elements is video. In the world of HTML and the web, viewing a video is as simple as using the native HTML element <video>.

In the context of applications, implementing video is not as easy as it is on the web. The good thing is that the React Native community has already developed very popular solutions to this problem.

This article highlights the most common package, react-native-video, for using video in your React Native app. You’ll also learn how to implement it into your React Native application.

Prerequisites

Because installation and usage may differ depending on the device you are developing for, we will focus on the iOS version and developing the app on a Mac-based developer environment for all of the examples.

Developing for various types of devices or platforms (e.g., Android) is similar, but the differences you need to be aware of are described in great detail in the package’s documentation.

What is react-native-video?

As of this writing, there is no real alternative to the most widely used package, react-native-video.

We made a custom demo for .
No really. Click here to check it out.

While I’m a fan of comparing different packages, that doesn’t make sense here, so we’ll just highlight the usage, pros, and cons of this library, then learn how to use it. The react-native-video package is 500kB in size and can be used on all devices in the React Native world.

Installing the package

Before you can use the library, you must install the package in the root directory of your project:

npm install --save react-native-video

If you are running your native React application on a Mac, you must also run the following command:

npx pod-install

For the other environments and application environments, please refer to the official installation guide for your platform.

Using react-native-video

Before I explain how to use the package, let’s start with an example of what we want to achieve with it. A common use case for videos in apps is dynamic backgrounds, which is what we want to achieve for our app in the login screen.

It should look something like this:

Login Page On Mobile Device Screen With Dynamic Animation Playing In The Background

First, we import the video component from the library into the component where we want the video to be displayed.

Of course, for the video component to display anything, we need a video file. This can either be a file in your project or a link to an external resource.

Now, let’s put everything together:

import Video from 'react-native-video';
import video from '../test-video.mp4';

const MyComponent = () => {
    return (
        <Video  
            source={video}                  // the video file
            paused={false}                  // make it start    
            style={styles.backgroundVideo}  // any style you want
            repeat={true}                   // make it a loop
        />
    )
}

As you can see, we have passed the imported video file from our project directly to the component. If you prefer a link to an external video file, you can also use the source prop, like so:

<Video  
    source={{ url: 'http://link-to-your-video.mp4'}}
    ...
/>

To achieve the look of the background video, we also passed some React Native styles to the component. Additionally, we set the prop pause to false, which tells the component to start the video right afterward. We also set the prop repeat to true, making the video loop.

Additional component props to use in react-native-video

We achieved our use case quite quickly by using only four props of the component. However, there are many more ways to use props. You can check the documentation to see the full list, but let me show you a selection of options that I find very useful.

allowsExternalPlayback

This prop allows the video to be controlled by external resources, such as AirPlay or HDMI, but this is only available on iOS.

playInBackground

Use this option to specify whether the video should continue to play when the application has been closed. Of course, only the audio will continue to play, but for some use cases, it can be helpful to keep the video playing even when the application has been closed.

poster

This prop creates an image that is shown when the video is loading or has not yet started, such as a thumbnail typically seen on YouTube. Additionally, you can adjust the image with posterResizeMode.

controls

In our example above, we didn’t want to show controls of the video because it was just running in the background, which is the default behavior of the component. If you want to allow the user to control the video, you can simply set controls to true and the controls will be displayed automatically.

Note: On iOS, the controls are displayed in full-screen mode even if this flag is set to false.

Creating external video controls

The component also provides everything you need to control the video from the outside, so it is possible to create your own unique user interface to control it.

The properties like paused, muted, volume, onprogress, or rate are props that you can customize using React state, and you can let any other element control them. Here’s a brief example of what I mean by this:

function Home(props) {  
    const [isPlaying, setIsPlaying] = React.useState(false);  
    const [isMuted, setIsMuted] = React.useState(false);  

    const togglePlaying = () => {};  

    return (  
        <View>  
            <Video
                source={video}  
                paused={!isPlaying}  
                controls={true}  
                style={styles.backgroundVideo}  
                muted={isMuted}  
            />  
            <Button
                onPress={() => setIsPlaying(p => !p)}  
                title={isPlaying ? 'Stop' : 'Play'}  
            />  
            <Button
                onPress={() => setIsMuted(m => !m)}  
                title={isMuted ? 'Unmute' : 'Mute'}  
            />  
        </View> 
    );  
}

As you can see, with a simple state and using buttons, we can control the video the way we want to, which gives us the ability to have a completely custom UI of the video.

Invoking methods in the video element

You can also invoke some methods in the video element to have more control over it, such as using actions like save to save the video to your device photos, or controlling the full-screen mode of the video.

To achieve this, you need to create a reference to the videoPlayer and store it for example in a useRef:

import Video from 'react-native-video';
import video from '../test-video.mp4';

const MyComponent = () => {
    const videoPlayer = React.useRef();

    const goFullScreen = () => {  
        if (videoPlayer.current) {  
            videoPlayer.current.presentFullscreenPlayer();  
        }  
    };

    return (
        <Video  
            ref={ref => (videoPlayer.current = ref)}
            source={video}                  // the video file
            paused={false}                  // make it start    
            style={styles.backgroundVideo}  // any style you want
            repeat={true}                   // make it a loop
        />
    )
}

Conclusion

React Native is a powerful tool because it offers the possibility to write your app using React, which is very similar to the one used on the web.

The only difference is that we don’t write HTML elements. We do, however, include native elements. Some of these elements are already included in the framework, but elements like videos must also be installed.

Although videos behave similarly to the web, developers need to consider building features such as full-screen mode or the option of resuming playback when the app is minimized.

The react-native-video library gives you all of these options so that you can easily add videos to your app and customize it, ensuring your users have a great experience when watching videos on your app!

: Full visibility into your web apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

.
Lorenz Weiß Hi, I'm Lorenz, a frontend-focused web developer. I'm in love with the internet and its people and interested in everything related to it.

Testing accessibility with Storybook

One big challenge when building a component library is prioritizing accessibility. Accessibility is usually seen as one of those “nice-to-have” features, and unfortunately, we’re...
Laura Carballo
4 min read

Leave a Reply