DEV Community

Tanvir Ahammed
Tanvir Ahammed

Posted on

1

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more