DEV Community

Tanvir Ahammed
Tanvir Ahammed

Posted on

How to set YouTube Video as Background in the Next.JS/React.Js app with styled component?

VideoBackground.tsx

import React from "react";
import styled from "styled-components";

const VIDEO_WIDTH = 1920;
const VIDEO_HEIGHT = 1080;

const VideoBackgroundWrapper = styled.div`
  position: relative;
  overflow: hidden;
  width: 100vw;
  height: 100vh;

  @media (min-aspect-ratio: 16/9) {
    --video-height: 56.25vw;
  }

  @media (max-aspect-ratio: 16/9) {
    --video-width: 177.78vh;
  }
`;

const VideoIframe = styled.iframe`
  position: absolute;
  top: 50%;
  left: 50%;
  width: var(--video-width, ${VIDEO_WIDTH}px);
  height: var(--video-height, ${VIDEO_HEIGHT}px);
  transform: translate(-50%, -50%);
`;

export const VideoBackground = ({ videoId, className }: any) => {
  const yt = `https://www.youtube.com/embed/${videoId}?autoplay=1&controls=0&mute=1&loop=1&modestbranding=1&showinfo=0&enablejsapi=1&&widgetid=3&playlist=${videoId}`;
  return (
    <VideoBackgroundWrapper className={className ?? ""}>
      <VideoIframe
        width={VIDEO_WIDTH}
        height={VIDEO_HEIGHT}
        src={yt}
        title="YouTube video player"
        frameBorder="0"
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
      />
    </VideoBackgroundWrapper>
  );
};

Enter fullscreen mode Exit fullscreen mode
app.tsx
export default function App() {
  return (
    <div className="video-layer">
      <VideoBackground
        className="image-layer"
        videoId={data?.videoId ?? "PtDIVU_tlo0"}
      />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)