How to apply CSS to subtitles in ReactPlayer?
Environment
<ReactPlayer
config={{
file: {
attributes: {},
tracks: [
{
label: 'subtitle',
kind: 'subtitles',
src: 'http://localhost:5173/sample.vtt',
srcLang: '',
default: true,
},
],
},
}}
/>
To apply custom CSS to subtitles in ReactPlayer, you need to use the file prop to include subtitle tracks, and then you can target the subtitle container using CSS. However, ReactPlayer does not expose direct props or options for styling subtitles, so you’ll have to use CSS selectors to style the subtitle elements after the player renders them.
Here’s a step-by-step guide to apply custom CSS to subtitles in ReactPlayer:
Step 1: Add Subtitles to ReactPlayer To add subtitles to your ReactPlayer, you need to include a track element inside the file prop. ReactPlayer supports WebVTT (.vtt) subtitle files.
import React from 'react';
import ReactPlayer from 'react-player';
const MyVideoPlayer = () => {
return (
<ReactPlayer
url="https://www.example.com/video.mp4"
controls
config={{
file: {
attributes: {
crossOrigin: 'anonymous', // Enable cross-origin if your video has external subtitles
},
tracks: [
{
kind: 'subtitles', // Type of track
src: 'https://www.example.com/subtitles-en.vtt', // Path to subtitle file
srcLang: 'en', // Language of subtitles
label: 'English', // Subtitle label
default: true // Make this subtitle the default one
}
]
}
}}
/>
);
};
export default MyVideoPlayer;
Step 2: Apply Custom CSS to Subtitles ReactPlayer doesn't expose a specific way to style subtitles directly via props. However, the subtitles are rendered inside a element, and you can target these elements with CSS. To do so:
You will typically see something like:
<div class="react-player">
<video>
<track kind="subtitles" src="" />
<!-- Other video elements -->
</video>
</div>
For example, to style the subtitles, you could write CSS like this:
::cue {
color: white;
font-size: 18px;
font-weight: bold;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}
::cue(region) {
background-color: rgba(0, 0, 0, 0.6);
padding: 2px 5px;
border-radius: 5px;
}
Step 3: Apply Custom CSS Globally or in a Specific Component To apply the styles globally, you can add the CSS to your global stylesheet (e.g., index.css or App.css).
If you want to apply styles to just one specific component, you could use inline styles or scoped CSS-in-JS libraries (e.g., styled-components or @emotion/react).
For example, if using plain CSS:
/* App.css or your component-specific stylesheet */
::cue {
color: yellow;
font-size: 20px;
text-shadow: 1px 1px 5px rgba(0, 0, 0, 0.7);
}
Notes:
By following these steps, you should be able to style the subtitles in ReactPlayer using CSS. Let me know if you need further clarification!