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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay