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 GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay