DEV Community

ali reza sadeghi
ali reza sadeghi

Posted on

2

Adding Subtitles to Videos in React: A Simple Tutorial by Alireza 🎉

By Alireza

Hey there, awesome coders! 👋 I’m Alireza, and today I’m going to walk you through how to add subtitles to a video in a React app. Subtitles are super helpful for making videos accessible or just adding some extra context. Don’t worry if you’re new to React, this tutorial is simple, and easy to follow. We’ll cover two ways to do this: using the ReactPlayer library and the native HTML <video> tag. Let’s dive in! 🚀

What You’ll Need

  • A React project set up (you can use create-react-app or any other setup).
  • A video file (we’ll use a sample URL).
  • A subtitle file in .vtt format (I’ll explain what that is soon).
  • Basic knowledge of React components.

Ready? Let’s get started! 😊


Step 1: Understanding Subtitles and the .vtt File

Before we code, let’s talk about subtitles. Subtitles are usually stored in a .vtt file (WebVTT format). It’s a simple text file that looks like this:


1
00:00:01.000 --> 00:00:04.000
Hello, welcome to my video!

2
00:00:04.001 --> 00:00:07.000
This is a simple subtitle example.

Enter fullscreen mode Exit fullscreen mode
  • WEBVTT is the header.
  • Each block has a number, a time range (like 00:00:01.000 --> 00:00:04.000), and the text to show.

You can create this file yourself with a text editor and save it as subtitles.vtt. For this tutorial, assume we have a subtitles.vtt file ready to use.


Option 1: Using ReactPlayer with Subtitles

First, let’s use the ReactPlayer library. It’s a popular, easy-to-use package for playing videos in React, and it supports subtitles out of the box.

Step 1.1: Install ReactPlayer

If you haven’t already, install ReactPlayer in your project. Open your terminal and run:

npm install react-player
Enter fullscreen mode Exit fullscreen mode

Step 1.2: Set Up Your Component

Create a new file called VideoPlayerWithSubtitles.js (or use an existing one). Here’s the code:

import React from 'react';
import ReactPlayer from 'react-player';
import subtitleFile from './subtitles.vtt'; // Import your .vtt file

const VideoPlayerWithSubtitles = () => {
  const videoUrl = 'your-video-url-here'; // Replace with your video URL

  return (
    <div style={{ width: '100%', maxWidth: '100%', overflow: 'hidden' }}>
      <ReactPlayer
        url={videoUrl}
        controls // Adds play/pause, volume, etc.
        width="100%" // Fits the container
        height="auto" // Keeps the video’s natural aspect ratio
        config={{
          file: {
            tracks: [
              {
                kind: 'subtitles', // Type of track
                src: subtitleFile, // Your imported .vtt file
                srcLang: 'en', // Language code (English)
                label: 'English', // What shows in the subtitle menu
                default: true, // Automatically turns subtitles on
              },
            ],
          },
        }}
      />
    </div>
  );
};

export default VideoPlayerWithSubtitles;
Enter fullscreen mode Exit fullscreen mode

Step 1.3: Add It to Your App

In your App.js or wherever you want the video, import and use the component:

import VideoPlayerWithSubtitles from './VideoPlayerWithSubtitles';

function App() {
  return (
    <div>
      <h1>Welcome to Alireza’s Video Player! 🎉</h1>
      <VideoPlayerWithSubtitles />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

How It Works

  • ReactPlayer takes a url prop for the video and a config object to set up subtitles.
  • The tracks array tells it where to find the .vtt file and how to display it.
  • The controls prop adds a built-in player interface where users can toggle subtitles.

When you run this, you’ll see a video player with subtitles that show up automatically. Cool, right? 😎


Option 2: Using the Native <video> Tag

If you don’t want to use a library, you can use the HTML <video> tag directly in React. It’s just as simple!

Step 2.1: Set Up Your Component

Here’s the code for the same VideoPlayerWithSubtitles.js file, but using <video>:

import React from 'react';

const VideoPlayerWithSubtitles = () => {
  const videoUrl = 'your-video-url-here'; // Replace with your video URL
  const subtitleUrl = 'your-subtitle-url-here'; // Replace with your .vtt URL

  return (
    <div style={{ width: '100%', maxWidth: '100%', overflow: 'hidden' }}>
      <video controls>
        <source src={videoUrl} type="video/mp4" />
        <track
          kind="subtitles"
          src={subtitleUrl}
          label="English"
          srcLang="en"
          default
        />
      </video>
    </div>
  );
};

export default VideoPlayerWithSubtitles;
Enter fullscreen mode Exit fullscreen mode

Step 2.2: Add It to Your App

Use it the same way as before in 'App.js':

import VideoPlayerWithSubtitles from './VideoPlayerWithSubtitles';

function App() {
  return (
    <div>
      <h1>Welcome to Alireza’s Video Player! 🎉</h1>
      <VideoPlayerWithSubtitles />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

How It Works

  • The <video> tag uses <source> for the video file and <track> for subtitles.
  • The controls attribute adds a basic player interface.
  • The track element links to your .vtt file and sets it as the default subtitle.

Note: For this method, the .vtt file needs to be hosted somewhere (like your server or a public URL), not imported like in ReactPlayer.


Which Option Should You Choose?

  • Use ReactPlayer if you want a quick setup with extra features (like YouTube support) and don’t mind adding a library.
  • Use <video> if you want a lightweight solution with no dependencies and full control over the HTML.

Both work great, and as Alireza, I’d say it depends on your project’s needs! 👍


Final Touches

  • Styling: Adjust the style prop or add CSS to make it look nice.
  • Testing: Try your video and subtitles in different browsers (Chrome, Firefox, etc.) to ensure they work.
  • Accessibility: Subtitles are already a win for accessibility—nice job! 🙌

That’s it! You’ve just learned how to add subtitles to a video in React, thanks to this tutorial by me, Alireza. Go ahead and try it out, and let me know how it goes. Happy coding! 🚀

Article by Alireza | React Specialist | Contact Me

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • 0:56 --last-failed
  • 2:34 --only-changed
  • 4:27 --repeat-each
  • 5:15 --forbid-only
  • 5:51 --ui --headed --workers 1

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Click on any timestamp above to jump directly to that section in the tutorial!

Watch Full Video 📹️

Top comments (0)

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • 0:56 --last-failed: Zero in on just the tests that failed in your previous run
  • 2:34 --only-changed: Test only the spec files you've modified in git
  • 4:27 --repeat-each: Run tests multiple times to catch flaky behavior before it reaches production
  • 5:15 --forbid-only: Prevent accidental test.only commits from breaking your CI pipeline
  • 5:51 --ui --headed --workers 1: Debug visually with browser windows and sequential test execution

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Click on any timestamp above to jump directly to that section in the tutorial!

Watch Full Video 📹️