I'm using the react-lite-youtube-embed
library to embed YouTube videos on my site. However, I'm running into an issue with the resolution of the video thumbnails. I want to ensure that the highest quality thumbnail available is used as the poster image.
Here's the relevant part of my code:
<LiteYouTubeEmbed id={videoId} poster={resolution}/>
To address this, I've come up with the following workaround:
// CSS importimport 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css';// React importsimport { useState } from "react";import Image from "next/image";const Video = ({ videoId }) => { const [resolution, setResolution] = useState("maxresdefault"); const handleError = () => { // Fallback to a lower resolution thumbnail setResolution("hqdefault"); }; return (<div><Image src={`https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`} height={0} width={0} onError={handleError} /><LiteYouTubeEmbed id={videoId} poster={resolution} /></div> );};export default Video;
This approach initially attempts to load the maxresdefault
thumbnail and falls back to the hqdefault
thumbnail if the higher resolution image is unavailable.
Question
Is there a more efficient or reliable way to achieve this? Ideally, I want to avoid manual fallbacks and have the component automatically select the highest quality available thumbnail (without fetching the data).
What did I try?
I tried preloading the highest resolution thumbnail (maxresdefault) using an component from next/image. If the high-resolution thumbnail fails to load, I use the onError handler to switch to a lower resolution (hqdefault).
What was I expecting?
I was hoping for a more seamless way to automatically select the highest quality available thumbnail without relying on manual fallbacks or extra components. Ideally, I want the react-lite-youtube-embed component to handle this internally (without fetching the data).