Latest Threat Research:Malicious dYdX Packages Published to npm and PyPI After Maintainer Compromise.Details β†’
Socket
Book a DemoInstallSign in
Socket

react-lite-youtube-embed

Package Overview
Dependencies
Maintainers
1
Versions
134
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-lite-youtube-embed

A private by default, faster and cleaner YouTube embed component for React applications

Source
npmnpm
Version
3.0.0
Version published
Weekly downloads
120K
3.01%
Maintainers
1
Weekly downloads
Β 
Created
Source

πŸ“Ί React Lite YouTube Embed

A private by default, faster and cleaner YouTube embed component for React applications

TypeScript

VersionΒ  Β Β  Β Total DownloadsΒ  Β Β  Β  Β  Β GitHub issues by-label

Automated Release Β  Β Β  Β  Β  Β  Deploy Demo to GitHub Pages

Developed in πŸ‡§πŸ‡· Brazil

Port of Paul Irish's Lite YouTube Embed to a React Component. Provide videos with a supercharged focus on visual performance. The gain is not the same as the web component of the original implementation but saves some requests and gives you more control of the embed visual. An "Adaptive Loading" way to handle iframes for YouTube.

iFrame example

✨ View Live Demo

Live demo automatically updated with each release - Try out all features and see code examples

πŸ”’ Up 2.0.0 Privacy by Default

The biggest change is, from 2.0.0 this component is private by default. Meaning that will not preconnect with the ad network from Google and connect to YouTube via the Privacy-Enhanced Mode using https://www.youtube-nocookie.com.

πŸš€ Install

Use your favorite package manager:

yarn add react-lite-youtube-embed
npm install react-lite-youtube-embed -S

πŸ•ΉοΈ Basic Usage

import React from "react";
import { render } from "react-dom";
import LiteYouTubeEmbed from 'react-lite-youtube-embed';
import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css';

const App = () => (
  <div>
    <LiteYouTubeEmbed
        id="L2vS_050c-M"
        title="What's new in Material Design for the web (Chrome Dev Summit 2019)"
    />
  </div>
);

render(<App />, document.getElementById("root"));

And that's it.

πŸ” SEO & Search Engine Optimization

Improve your video discoverability in search engines with structured data and fallback links.

Why SEO Matters

By default, search engine crawlers cannot discover videos embedded with lite embeds because:

  • No followable links exist before user interaction
  • No structured metadata for search engines to index
  • The facade pattern is invisible to crawlers

This component now supports JSON-LD structured data and noscript fallbacks to solve these issues.

Basic SEO Setup

<LiteYouTubeEmbed
  id="L2vS_050c-M"
  title="What's new in Material Design"
  seo={{
    name: "What's new in Material Design for the web",
    description: "Learn about the latest Material Design updates presented at Chrome Dev Summit 2019",
    uploadDate: "2019-11-11T08:00:00Z",
    duration: "PT15M33S"
  }}
/>

This will generate:

  • βœ… JSON-LD structured data following schema.org VideoObject
  • βœ… Noscript fallback with direct YouTube link (enabled by default)
  • βœ… Google rich results eligibility (video carousels, thumbnails in search)

Fetching Video Metadata

Use the included helper script to quickly fetch video metadata:

# Make the script executable (first time only)
chmod +x scripts/fetch-youtube-metadata.sh

# Fetch metadata in JSON format
./scripts/fetch-youtube-metadata.sh dQw4w9WgXcQ

# Get ready-to-use React component code
./scripts/fetch-youtube-metadata.sh dQw4w9WgXcQ --format react

Requirements: curl and jq must be installed.

The script uses YouTube's oEmbed API (no auth required) and provides:

  • Video title
  • Thumbnail URL
  • Template with TODO fields for description, upload date, and duration

Manual Metadata Collection

For complete metadata, you can:

  • Visit the video page and manually copy:

    • Description
    • Upload date (convert to ISO 8601: YYYY-MM-DDTHH:MM:SSZ)
    • Duration (convert to ISO 8601: PT#H#M#S)
  • Use YouTube Data API v3 (get free API key):

    curl "https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=VIDEO_ID&key=YOUR_API_KEY"
    
  • Browser DevTools approach:

    • Open video page β†’ Inspect β†’ Search for "datePublished" and "duration" in HTML

Duration Format Examples

ISO 8601 duration format: PT#H#M#S

  • "PT3M33S" - 3 minutes 33 seconds
  • "PT15M" - 15 minutes
  • "PT1H30M" - 1 hour 30 minutes
  • "PT2H15M30S" - 2 hours 15 minutes 30 seconds

SEO Prop Reference

interface VideoSEO {
  name?: string;           // Video title (falls back to title prop)
  description?: string;    // Video description (50-160 chars recommended)
  uploadDate?: string;     // ISO 8601 date (e.g., "2024-01-15T08:00:00Z")
  duration?: string;       // ISO 8601 duration (e.g., "PT3M33S")
  thumbnailUrl?: string;   // Custom thumbnail (auto-generated if omitted)
  contentUrl?: string;     // YouTube watch URL (auto-generated)
  embedUrl?: string;       // Embed URL (auto-generated)
}

Disabling Noscript Fallback

The noscript fallback is enabled by default. To disable:

<LiteYouTubeEmbed
  id="L2vS_050c-M"
  title="Video Title"
  noscriptFallback={false}
/>

Verify Your SEO Setup

Test your structured data with Google's tools:

Note: Playlists do not support SEO structured data (only individual videos).

πŸ’Ž Pro Usage

const App = () => (
  <div>
    <LiteYouTubeEmbed
       id="L2vS_050c-M" // Default none, id of the video or playlist
       adNetwork={false} // Default false, to preconnect or not to doubleclick addresses called by YouTube iframe (the adnetwork from Google)
       params="" // any params you want to pass to the URL, assume we already had '&' and pass your parameters string
       playlist={false} // Use true when your ID be from a playlist
       playlistCoverId="L2vS_050c-M" // The ids for playlists did not bring the cover in a pattern to render so you'll need pick up a video from the playlist (or in fact, whatever id) and use to render the cover. There's a programmatic way to get the cover from YouTube API v3 but the aim of this component is do not make any another call and reduce requests and bandwidth usage as much as possibe
       poster="hqdefault" // Defines the image size to call on first render as poster image. Possible values are "default","mqdefault",  "hqdefault", "sddefault" and "maxresdefault". Default value for this prop is "hqdefault". Please be aware that "sddefault" and "maxresdefault", high resolution images are not always avaialble for every video. See: https://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
       title="YouTube Embed" // a11y, always provide a title for iFrames: https://dequeuniversity.com/tips/provide-iframe-titles Help the web be accessible ;)
       cookie={false} // Default false, don't connect to YouTube via the Privacy-Enhanced Mode using https://www.youtube-nocookie.com
       ref={myRef} // Access the iframe element. Only available after user clicks the poster (use onIframeAdded callback to know when ready). See "Using Refs" section below for examples
    />
  </div>
);

⚑ Performance: Lazy Loading

Improve Lighthouse scores and reduce bandwidth by enabling lazy loading for thumbnail images:

<LiteYouTubeEmbed
  id="L2vS_050c-M"
  title="What's new in Material Design"
  lazyLoad={true}
/>

How it works:

  • Default behavior (lazyLoad={false}): Uses CSS background-image with preload link
  • With lazy loading (lazyLoad={true}): Uses <img loading="lazy"> for native browser lazy loading

Benefits:

  • βœ… Defers loading of offscreen images
  • βœ… Reduces initial page bandwidth (especially for pages with multiple videos)
  • βœ… Improves Lighthouse "defer offscreen images" score
  • βœ… Better mobile performance on slow connections
  • βœ… 97%+ browser support

When to use:

  • Pages with multiple YouTube embeds
  • Videos placed below the fold
  • Mobile-first applications
  • Performance-critical pages

Example with multiple embeds:

const VideoGallery = () => (
  <div>
    <LiteYouTubeEmbed
      id="dQw4w9WgXcQ"
      title="Video 1"
      lazyLoad
    />
    <LiteYouTubeEmbed
      id="L2vS_050c-M"
      title="Video 2"
      lazyLoad
    />
    {/* Only loads visible thumbnails initially */}
  </div>
);

🧰 Bring Your Own Styles

React Lite YouTube Embed comes with all original styles from Paul Irish's Lite YouTube Embed but you can customize them as you wish passing as a props.

const App = () => (
  <div>
    <LiteYouTubeEmbed
       id="L2vS_050c-M"
       activeClass="lyt-activated" // Default as "lyt-activated", gives control to wrapper once clicked
       iframeClass="" // Default none, gives control to add a class to iframe element itself
       playerClass="lty-playbtn" // Default as "lty-playbtn" to control player button styles
       wrapperClass="yt-lite" // Default as "yt-lite" for the div wrapping the area, the most important class and needs extra attention, please refer to LiteYouTubeEmbed.css for a reference.
    />
  </div>
);

πŸ€– Controlling the player

You can programmatically control the YouTube player via YouTubes IFrame Player API. However typically YouTube requires you to load an additional script from their servers (https://www.youtube.com/iframe_api), which is small but it will load another script. So this is neither performant nor very privacy-friendly. Instead, you can also send messages to the iframe via (postMessage)[https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage] using the ref prop. If you don't want to create the postMessage() calls yourself, there is also a little (wrapper library)[https://github.com/mich418/youtube-iframe-ctrl] for controlling the iframe with this method.

[!WARNING]
This will only work if you set the enableJsApi prop to true. Also, the ref will only be defined, when the iframe has been loaded (which happens after clicking on the poster). So you can't start the player through this method. If you really want the player to always load the iframe right away (which is not good in terms of privacy), you can use the alwaysLoadIframe prop to do this.

const App = () => (
  const ytRef = useRef(null);
  const [isPlaying, setIsPlaying] = useState(false);

  return (
    <div>
      <button
        onClick={() => {
          setIsPlaying((oldState) => !oldState);
          ytRef.current?.contentWindow?.postMessage(
            `{"event": "command", "func": "${isPlaying ? "pauseVideo" : "playVideo"}"}`,
            "*",
          );
        }}
      >
        External Play Button
      </button>
      <LiteYouTubeEmbed
        title="My Video"
        id="L2vS_050c-M"
        ref={ytRef}
        enableJsApi
        alwaysLoadIframe
      />
    </div>
  );
};
);

🎯 Using Refs with Lazy-Loaded Iframes

Important: The ref only becomes available after the user clicks the poster image, since the iframe is lazy-loaded for performance and privacy.

❌ Common Mistake

const videoRef = useRef(null);

useEffect(() => {
  // This will NEVER log - iframe doesn't exist on mount!
  if (videoRef.current) {
    console.log("iframe ref"); // Never runs
  }
}, []); // Empty deps - runs only once on mount, before iframe exists

return <LiteYouTubeEmbed id="L2vS_050c-M" title="My Video" ref={videoRef} />;

Why this doesn't work: The iframe is only rendered after user interaction (clicking the poster). Your useEffect with empty dependencies runs once on mount, but the iframe doesn't exist yet.

βœ… Correct Approaches

This is the cleanest way to know when the iframe is ready:

const videoRef = useRef(null);

const handleIframeAdded = () => {
  console.log("Iframe loaded and ready!");

  // Now you can safely access the ref
  if (videoRef.current) {
    console.log("Iframe element:", videoRef.current);

    // Control the player via postMessage
    videoRef.current.contentWindow?.postMessage(
      '{"event":"command","func":"playVideo"}',
      '*'
    );
  }
};

return (
  <LiteYouTubeEmbed
    id="L2vS_050c-M"
    title="My Video"
    ref={videoRef}
    onIframeAdded={handleIframeAdded}
    enableJsApi
  />
);

Option 2: Watch for Ref Changes

Monitor when the ref becomes available:

const videoRef = useRef(null);

useEffect(() => {
  if (videoRef.current) {
    console.log("Iframe is now available!");
    // Do something with videoRef.current
  }
}, [videoRef.current]); // Re-run when ref changes

Force the iframe to load immediately, bypassing lazy-loading:

// ⚠️ This defeats the performance and privacy benefits!
<LiteYouTubeEmbed
  id="L2vS_050c-M"
  title="My Video"
  ref={videoRef}
  alwaysLoadIframe
  enableJsApi
/>

Trade-off: With alwaysLoadIframe={true}, the ref is available immediately, but you lose the performance benefits and load YouTube resources on page load.

Real-World Example

Controlling the player after the user activates it:

function VideoPlayer() {
  const playerRef = useRef(null);
  const [isReady, setIsReady] = useState(false);

  const handleIframeAdded = () => {
    setIsReady(true);
    console.log("Player is ready for commands");
  };

  const togglePlayPause = () => {
    if (playerRef.current && isReady) {
      playerRef.current.contentWindow?.postMessage(
        '{"event":"command","func":"pauseVideo"}',
        '*'
      );
    }
  };

  return (
    <div>
      <LiteYouTubeEmbed
        id="L2vS_050c-M"
        title="My Video"
        ref={playerRef}
        onIframeAdded={handleIframeAdded}
        enableJsApi
      />
      {isReady && (
        <button onClick={togglePlayPause}>
          Pause Video
        </button>
      )}
    </div>
  );
}

🎬 Player Events (New in v3.0)

Get real-time notifications when the YouTube player changes state, encounters errors, or when users interact with playback controls. All event handlers require enableJsApi={true} to work.

Quick Start

import LiteYouTubeEmbed, { PlayerState, PlayerError } from 'react-lite-youtube-embed';

function App() {
  return (
    <LiteYouTubeEmbed
      id="dQw4w9WgXcQ"
      title="Rick Astley - Never Gonna Give You Up"
      enableJsApi

      // Simple convenience handlers
      onPlay={() => console.log('Video started playing')}
      onPause={() => console.log('Video paused')}
      onEnd={() => console.log('Video ended')}

      // Advanced state change handler
      onStateChange={(event) => {
        console.log('State:', event.state);
        console.log('Current time:', event.currentTime);
      }}

      // Error handling
      onError={(errorCode) => {
        if (errorCode === PlayerError.VIDEO_NOT_FOUND) {
          alert('Video not available');
        }
      }}
    />
  );
}

Available Event Handlers

Core Events

onReady(event: PlayerReadyEvent) Fires when the player is loaded and ready to receive commands. This is the first event you'll receive.

onReady={(event) => {
  console.log(`Player ready for: ${event.videoId}`);
  // Safe to call player methods now
}}

onStateChange(event: PlayerStateChangeEvent) Fires whenever the player's state changes (playing, paused, ended, buffering, etc.). Use this for comprehensive state tracking.

onStateChange={(event) => {
  switch (event.state) {
    case PlayerState.PLAYING:
      console.log('Playing at', event.currentTime, 'seconds');
      break;
    case PlayerState.PAUSED:
      console.log('Paused');
      break;
    case PlayerState.ENDED:
      console.log('Video finished');
      break;
    case PlayerState.BUFFERING:
      console.log('Buffering...');
      break;
  }
}}

Available PlayerState values:

  • PlayerState.UNSTARTED (-1)
  • PlayerState.ENDED (0)
  • PlayerState.PLAYING (1)
  • PlayerState.PAUSED (2)
  • PlayerState.BUFFERING (3)
  • PlayerState.CUED (5)

onError(errorCode: PlayerError) Fires when the player encounters an error. Use this for graceful error handling.

onError={(code) => {
  switch (code) {
    case PlayerError.INVALID_PARAM:
      console.error('Invalid video parameter');
      break;
    case PlayerError.VIDEO_NOT_FOUND:
      console.error('Video not found or removed');
      break;
    case PlayerError.NOT_EMBEDDABLE:
      console.error('Video cannot be embedded');
      break;
  }
}}

Available PlayerError codes:

  • PlayerError.INVALID_PARAM (2) - Invalid parameter value
  • PlayerError.HTML5_ERROR (5) - HTML5 player error
  • PlayerError.VIDEO_NOT_FOUND (100) - Video not found or removed
  • PlayerError.NOT_EMBEDDABLE (101) - Video owner disabled embedding
  • PlayerError.NOT_EMBEDDABLE_DISGUISED (150) - Same as 101 (used in disguised mode)

Convenience Events

These are simple wrappers around onStateChange for common use cases. They don't receive any parameters.

onPlay() - Video started playing onPause() - Video was paused onEnd() - Video finished playing onBuffering() - Video is buffering

<LiteYouTubeEmbed
  id="dQw4w9WgXcQ"
  title="My Video"
  enableJsApi
  onPlay={() => analytics.track('video_play')}
  onPause={() => analytics.track('video_pause')}
  onEnd={() => loadNextVideo()}
  onBuffering={() => showLoadingSpinner()}
/>

Advanced Events

onPlaybackRateChange(playbackRate: number) Fires when the user changes playback speed. Common values: 0.25, 0.5, 1, 1.5, 2.

onPlaybackRateChange={(rate) => {
  console.log(`Playback speed: ${rate}x`);
}}

onPlaybackQualityChange(quality: string) Fires when video quality changes. Values: "small" (240p), "medium" (360p), "large" (480p), "hd720", "hd1080", etc.

onPlaybackQualityChange={(quality) => {
  console.log(`Quality changed to: ${quality}`);
  analytics.track('quality_change', { quality });
}}

Real-World Examples

Analytics Tracking

function VideoWithAnalytics() {
  const [playStartTime, setPlayStartTime] = useState(null);

  return (
    <LiteYouTubeEmbed
      id="dQw4w9WgXcQ"
      title="My Video"
      enableJsApi
      onReady={() => {
        analytics.track('video_ready');
      }}
      onPlay={() => {
        setPlayStartTime(Date.now());
        analytics.track('video_play');
      }}
      onPause={() => {
        analytics.track('video_pause');
      }}
      onEnd={() => {
        const watchTime = Date.now() - playStartTime;
        analytics.track('video_complete', { watchTime });
      }}
      onError={(code) => {
        analytics.track('video_error', { errorCode: code });
      }}
    />
  );
}

Video Playlist with Auto-Advance

function VideoPlaylist() {
  const videos = ['dQw4w9WgXcQ', 'abc123def', 'xyz789uvw'];
  const [currentIndex, setCurrentIndex] = useState(0);

  const handleVideoEnd = () => {
    if (currentIndex < videos.length - 1) {
      setCurrentIndex(currentIndex + 1);
    }
  };

  return (
    <LiteYouTubeEmbed
      id={videos[currentIndex]}
      title={`Video ${currentIndex + 1}`}
      enableJsApi
      onEnd={handleVideoEnd}
      onError={(code) => {
        console.error(`Error with video ${currentIndex}:`, code);
        // Skip to next video on error
        handleVideoEnd();
      }}
    />
  );
}

Custom Play/Pause UI

function CustomControls() {
  const [isPlaying, setIsPlaying] = useState(false);
  const [isReady, setIsReady] = useState(false);

  return (
    <div>
      <LiteYouTubeEmbed
        id="dQw4w9WgXcQ"
        title="My Video"
        enableJsApi
        alwaysLoadIframe  // Required for external controls
        onReady={() => setIsReady(true)}
        onPlay={() => setIsPlaying(true)}
        onPause={() => setIsPlaying(false)}
        onEnd={() => setIsPlaying(false)}
      />

      {isReady && (
        <div className="custom-controls">
          <span>{isPlaying ? '▢️ Playing' : '⏸️ Paused'}</span>
        </div>
      )}
    </div>
  );
}

Important Notes

⚠️ Events require enableJsApi={true} - All event handlers require this prop to be enabled.

⚠️ Lazy Loading Limitation - By default, the iframe only loads after the user clicks the poster. This means:

  • Events won't fire until after user interaction
  • Use onIframeAdded callback to know when the iframe is ready
  • Or use alwaysLoadIframe={true} if you need events immediately (not recommended for privacy/performance)

⚠️ Origin Validation - The component automatically validates that events come from YouTube domains (youtube.com or youtube-nocookie.com) for security.

⚠️ Cleanup - Event listeners are automatically cleaned up when the component unmounts.

⚠️ After version 1.0.0 - BREAKING CHANGES ⚠️

To play nice with new frameworks like NextJS, we now don't import the .css necessary. Since version 2.0.9 you can pass custom aspect-ratio props, so be aware of any changes needed in the CSS options. Instead use now you have three options:

πŸ“˜ Using Next.js or SSR? Check out the SSR Guide for setup instructions, troubleshooting, and best practices.

Option 1

Place the necessary CSS in your Global CSS file method of preference

Show me the code!
.yt-lite {
    background-color: #000;
    position: relative;
    display: block;
    contain: content;
    background-position: center center;
    background-size: cover;
    cursor: pointer;
}

/* gradient */
.yt-lite::before {
    content: '';
    display: block;
    position: absolute;
    top: 0;
    background-position: top;
    background-repeat: repeat-x;
    height: 60px;
    padding-bottom: 50px;
    width: 100%;
    transition: all 0.2s cubic-bezier(0, 0, 0.2, 1);
}

/* responsive iframe with a 16:9 aspect ratio
    thanks https://css-tricks.com/responsive-iframes/
*/
.yt-lite::after {
    content: "";
    display: block;
    padding-bottom: calc(100% / (16 / 9));
}
.yt-lite > iframe {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

/* play button */
.yt-lite > .lty-playbtn {
    width: 65px;
    height: 46px;
    z-index: 1;
    opacity: 0.8;
    border: none;
    background: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20version%3D%221.1%22%20id%3D%22YouTube_Icon%22%20x%3D%220px%22%20y%3D%220px%22%20viewBox%3D%220%200%201024%20721%22%20enable-background%3D%22new%200%200%201024%20721%22%20xml%3Aspace%3D%22preserve%22%3E%3Cscript%20xmlns%3D%22%22%3E%0A%20%20%20%20try%20%7B%0A%20%20%20%20%20%20Object.defineProperty(navigator%2C%20%22globalPrivacyControl%22%2C%20%7B%0A%20%20%20%20%20%20%20%20value%3A%20false%2C%0A%20%20%20%20%20%20%20%20configurable%3A%20false%2C%0A%20%20%20%20%20%20%20%20writable%3A%20false%0A%20%20%20%20%20%20%7D)%3B%0A%20%20%20%20%20%20document.currentScript.parentElement.removeChild(document.currentScript)%3B%0A%20%20%20%20%7D%20catch(e)%20%7B%7D%3B%0A%20%20%20%20%20%20%3C%2Fscript%3E%0A%3Cpath%20id%3D%22Triangle%22%20fill%3D%22%23FFFFFF%22%20d%3D%22M407%2C493l276-143L407%2C206V493z%22%2F%3E%0A%3Cpath%20id%3D%22The_Sharpness%22%20opacity%3D%220.12%22%20fill%3D%22%23420000%22%20d%3D%22M407%2C206l242%2C161.6l34-17.6L407%2C206z%22%2F%3E%0A%3Cg%20id%3D%22Lozenge%22%3E%0A%09%3Cg%3E%0A%09%09%0A%09%09%09%3ClinearGradient%20id%3D%22SVGID_1_%22%20gradientUnits%3D%22userSpaceOnUse%22%20x1%3D%22512.5%22%20y1%3D%22719.7%22%20x2%3D%22512.5%22%20y2%3D%221.2%22%20gradientTransform%3D%22matrix(1%200%200%20-1%200%20721)%22%3E%0A%09%09%09%3Cstop%20offset%3D%220%22%20style%3D%22stop-color%3A%23E52D27%22%2F%3E%0A%09%09%09%3Cstop%20offset%3D%221%22%20style%3D%22stop-color%3A%23BF171D%22%2F%3E%0A%09%09%3C%2FlinearGradient%3E%0A%09%09%3Cpath%20fill%3D%22url(%23SVGID_1_)%22%20d%3D%22M1013%2C156.3c0%2C0-10-70.4-40.6-101.4C933.6%2C14.2%2C890%2C14%2C870.1%2C11.6C727.1%2C1.3%2C512.7%2C1.3%2C512.7%2C1.3%20%20%20%20h-0.4c0%2C0-214.4%2C0-357.4%2C10.3C135%2C14%2C91.4%2C14.2%2C52.6%2C54.9C22%2C85.9%2C12%2C156.3%2C12%2C156.3S1.8%2C238.9%2C1.8%2C321.6v77.5%20%20%20%20C1.8%2C481.8%2C12%2C564.4%2C12%2C564.4s10%2C70.4%2C40.6%2C101.4c38.9%2C40.7%2C89.9%2C39.4%2C112.6%2C43.7c81.7%2C7.8%2C347.3%2C10.3%2C347.3%2C10.3%20%20%20%20s214.6-0.3%2C357.6-10.7c20-2.4%2C63.5-2.6%2C102.3-43.3c30.6-31%2C40.6-101.4%2C40.6-101.4s10.2-82.7%2C10.2-165.3v-77.5%20%20%20%20C1023.2%2C238.9%2C1013%2C156.3%2C1013%2C156.3z%20M407%2C493V206l276%2C144L407%2C493z%22%2F%3E%0A%09%3C%2Fg%3E%0A%3C%2Fg%3E%0A%3C%2Fsvg%3E");
    transition: all 0.2s cubic-bezier(0, 0, 0.2, 1);
}
.yt-lite:hover > .lty-playbtn {
    opacity: 1;
}
/* play button triangle */
.yt-lite > .lty-playbtn:before {
    content: '';
    border-style: solid;
    border-width: 11px 0 11px 19px;
    border-color: transparent transparent transparent #fff;
}

.yt-lite > .lty-playbtn,
.yt-lite > .lty-playbtn:before {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate3d(-50%, -50%, 0);
}

/* Post-click styles */
.yt-lite.lyt-activated {
    cursor: unset;
}
.yt-lite.lyt-activated::before,
.yt-lite.lyt-activated > .lty-playbtn {
    opacity: 0;
    pointer-events: none;
}

For example, for NextJS:

<style jsx global>{`
        html,
        body {
          padding: 0;
          margin: 0;
          font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
            Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue,
            sans-serif;
        }

        * {
          box-sizing: border-box;

        // CSS above

`}</style>

Option 2

Using your CSS-In-JS tool of choice encapsulate this component and use the css provided as a guide.

Option 3

Not work on every framework but you can import the css directly, check what works best with your bundler / framework.

Show me the code!
import 'react-lite-youtube-embed/dist/index.css';

or in a *.css/scss etc:

@import "~react-lite-youtube-embed/dist/index.css";

All our props belongs to you

The most minimalist implementation requires two props: id from the YouTube you want to render and title, for the iFrame.

PropTypeDefaultDescription
idstring-Required. ID of the video or playlist
titlestring-Required. Video title for the iFrame. Always provide a title for iFrames: https://dequeuniversity.com/tips/provide-iframe-titles Help the web be accessible ;) #a11y
activeClassstring"lyt-activated"Pass the string class for the active state
adNetworkbooleanfalseTo preconnect or not to doubleclick addresses called by YouTube iframe (the adnetwork from Google)
alwaysLoadIframebooleanfalseIf enabled, the original YouTube iframe will always be loaded right away (not recommended for privacy)
announcestring"Watch"Text added to the button for screen readers as Clickable {announce}, {title}, button. Customize to match your language #a11y #i18n
aspectHeightnumber9Use this optional prop if you want a custom aspect-ratio. Please be aware of aspect height and width relation and also any custom CSS you are using
aspectWidthnumber16Use this optional prop if you want a custom aspect-ratio. Please be aware of aspect height and width relation and also any custom CSS you are using
autoplaybooleanfalseEnables autoplay videos. Important: only works with muted={true} and alwaysLoadIframe={true}
containerElementstring"article"The HTML element to be used for the container
cookiebooleanfalseSet to true to use https://www.youtube.com instead of Privacy-Enhanced Mode (https://www.youtube-nocookie.com)
enableJsApibooleanfalseIf enabled, you can send messages to the iframe (via the ref prop) to control the player programmatically
focusOnLoadbooleanfalseAutomatically focus iframe when loaded (useful for keyboard navigation)
iframeClassstring""Pass the string class for the iframe element itself
lazyLoadbooleanfalseEnable native lazy loading for thumbnail images. Improves Lighthouse scores and reduces bandwidth for below-fold videos. Uses <img loading="lazy"> instead of CSS background-image
mutedbooleanfalseIf the video has sound or not. Required for autoplay={true} to work
noCookiebooleanfalse⚠️ DEPRECATED - Use cookie prop instead
noscriptFallbackbooleantrueInclude noscript tag with YouTube link for accessibility and SEO crawlers
onBufferingfunctionundefined[Event] Fires when video is buffering. Requires enableJsApi={true}. See Player Events
onEndfunctionundefined[Event] Fires when video ends. Requires enableJsApi={true}. See Player Events
onErrorfunctionundefined[Event] Fires on player errors with error code. Requires enableJsApi={true}. See Player Events
onIframeAddedfunctionundefinedCallback fired when iframe loads. Use this to know when the ref becomes available (ref is only populated after user clicks the poster). See Using Refs section for examples
onPausefunctionundefined[Event] Fires when video is paused. Requires enableJsApi={true}. See Player Events
onPlayfunctionundefined[Event] Fires when video starts playing. Requires enableJsApi={true}. See Player Events
onPlaybackQualityChangefunctionundefined[Event] Fires when video quality changes. Requires enableJsApi={true}. See Player Events
onPlaybackRateChangefunctionundefined[Event] Fires when playback speed changes. Requires enableJsApi={true}. See Player Events
onReadyfunctionundefined[Event] Fires when player is ready. Requires enableJsApi={true}. See Player Events
onStateChangefunctionundefined[Event] Fires on all state changes (play/pause/end/buffering). Requires enableJsApi={true}. See Player Events
paramsstring""Additional params to pass to the URL. Format: start=1150&other=value. Don't include ? or leading &. Note: use start not t for time
playerClassstring"lty-playbtn"Pass the string class for the player button to customize it
playlistbooleanfalseSet to true when your id is from a playlist
playlistCoverIdstringundefinedVideo ID to use for playlist cover image. Playlists don't have a standard cover pattern
poster"default" | "mqdefault" | "hqdefault" | "sddefault" | "maxresdefault""hqdefault"Defines the image size for the poster. Note: sddefault and maxresdefault aren't always available. See: YouTube API docs
referrerPolicystring"strict-origin-when-cross-origin"Sets the referrer policy for the iframe
relstring"preload"⚠️ DEPRECATED - Use resourceHint prop instead. This prop name conflicts with YouTube's rel parameter
resourceHint"preload" | "prefetch""preload"Controls resource hint for the poster image link tag. Use "prefetch" for lower priority or "preload" for higher priority loading
seoVideoSEOundefinedSEO metadata for search engines. Generates JSON-LD structured data. See SEO section for details
stopOnEndbooleanfalseAutomatically stop video when it ends to prevent showing related videos. Requires enableJsApi={true}. See FAQ for details
styleobject{}Style object for the container, overriding any root styles
thumbnailstringundefinedPass an optional image url to override the default poster and set a custom poster image
webpbooleanfalseWhen set, uses the WebP format for poster images
wrapperClassstring"yt-lite"Pass the string class that wraps the iFrame. Important: This class needs extra attention, refer to LiteYouTubeEmbed.css

❓ Frequently Asked Questions

Can I completely hide suggested/related videos after my video ends?

Unfortunately, no - this is a YouTube platform limitation that affects all embed implementations, not just this library.

What changed: In September 2018, YouTube changed how the rel=0 parameter works. It no longer hides all related videosβ€”it only limits them to videos from the same channel.

Available options:

Option 1: Limit to same-channel videos (partial solution)

Use the params prop to add rel=0:

<LiteYouTubeEmbed
  id="VIDEO_ID"
  title="Video Title"
  params="rel=0"
/>

Note: This only shows videos from your channel. If your channel has many videos, related videos will still appear.

Option 2: Use the built-in stopOnEnd prop (easiest solution)

The easiest way to prevent related videos is to use the built-in stopOnEnd feature:

<LiteYouTubeEmbed
  id="VIDEO_ID"
  title="Video Title"
  enableJsApi={true}
  stopOnEnd={true}
  params="rel=0"
/>

How it works:

  • Automatically stops the video when it ends
  • Returns the player to the thumbnail view
  • Prevents related videos from showing
  • Requires enableJsApi={true} to work

Benefits:

  • βœ… No manual event handling needed
  • βœ… Works out of the box
  • βœ… Cleaner code

Option 3: Manual YouTube Player API control (advanced solution)

For more control, you can manually handle the YouTube Player API events:

import { useRef, useEffect } from 'react';
import LiteYouTubeEmbed from 'react-lite-youtube-embed';

const App = () => {
  const ytRef = useRef(null);

  useEffect(() => {
    // Listen for messages from the YouTube iframe
    const handleMessage = (event) => {
      if (event.origin !== 'https://www.youtube.com' &&
          event.origin !== 'https://www.youtube-nocookie.com') return;

      try {
        const data = JSON.parse(event.data);
        // Check if video ended (state 0)
        if (data.info?.playerState === 0) {
          // Stop the video to return to thumbnail
          ytRef.current?.contentWindow?.postMessage(
            '{"event":"command","func":"stopVideo","args":""}',
            '*'
          );
        }
      } catch (e) {
        // Not JSON, ignore
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, []);

  return (
    <LiteYouTubeEmbed
      id="VIDEO_ID"
      title="Video Title"
      ref={ytRef}
      enableJsApi={true}
      params="rel=0"
    />
  );
};

How it works:

  • Enable the YouTube IFrame API with enableJsApi={true}
  • Listen for playerState changes via postMessage
  • When the video ends (state 0), send stopVideo command
  • The player returns to the thumbnail, preventing related videos from showing

See the πŸ€– Controlling the player section for more details on using the YouTube IFrame API.

Related: Issue #94

YouTube changed this behavior in September 2018 for business reasons. The embed API no longer provides any parameter to completely disable related videos.

From YouTube's official documentation:

"If the rel parameter is set to 0, related videos will come from the same channel as the video that was just played."

This is a permanent platform change that affects all YouTube embeds, not just this library.

πŸ™‡β€β™‚οΈ Thanks

πŸ“ Read more

MIT License

Copyright (c) 2021 β€” 2025 Ibrahim Cesar

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Keywords

React

FAQs

Package last updated on 15 Nov 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts