[개인프로젝트] 비디오 배너 생성(Iframe 컴포넌트)

배상건·2023년 3월 16일
0

프로젝트

목록 보기
7/10
post-thumbnail

목표

  1. the movie DB API로 받아온 영화 데이터 중 비디오 데이터를 배너 컴포넌트에서 재생하려고 한다.
  2. 비디오 데이터가 있을 경우, 배너에 Play 버튼이 활성화 된다.
  3. 해당 버튼을 클릭하여, 비디오를 재생한다.

방법

  1. Play 버튼을 클릭하면, 기존의 배너 React Element 랜더링하지 않고,
    비디오 React Element가 랜더링되도록 조건문을 설정한다.
  2. 조건문은 Play 버튼에 클릭이벤트가 발생했는지 여부를 파단한다.
  3. 따라서, Play 버튼의 클릭 이벤트 활성화 유무를 상태로 관리해야한다.

적용

import React, { useEffect, useState } from "react";
import { fetchData } from "../api/axios";
import {
  HeaderBanner,
  BannerContents,
  BannerTitle,
  BannerButtons,
  BannerButton,
  BannerDescription,
  BannerFadeBottom,
} from "./Banner.styled";

const Banner = () => {
  const [movie, setMovie] = useState([]);
  /* play 버튼 클릭 여부 상태 */
  const [isClicked, setClicked] = useState(false); 
  useEffect(() => {
    fetchData(setMovie);
  }, []);

  // Description 컴포넌트 내
  // 설명글이 100자 이상이면, 100자 이전 까지 자른 후, 100자부터 "..."로 마무리한다.
  const truncatOverview = (str, n) => {
    return str?.length > n ? str.substring(0, n) + "..." : str;
  };

  const playHandle = (e) => setClicked(true);
  /* play 버튼이 클릭되었다면(true) video string react element 랜더링 */
  if (isClicked) {
    console.log(isClicked);
    return <div>video!</div>;
  }

  return (
    <HeaderBanner
      movie={`https://image.tmdb.org/t/p/original/${movie.backdrop_path}`}
    >
      <BannerContents>
        <BannerTitle>
          {movie.title || movie.name || movie.original_name}
        </BannerTitle>
        <BannerButtons>
          {movie?.videos?.results[0]?.key && (
            <BannerButton play onClick={playHandle}>
              Play
            </BannerButton>
          )}
        </BannerButtons>
        <BannerDescription>
          {truncatOverview(movie?.overview, 100)}
        </BannerDescription>
      </BannerContents>
      <BannerFadeBottom />
    </HeaderBanner>
  );
};

export default Banner;

결과1.

원하는 결과를 얻을 수 있었다.
이제 video react element를 만들면 된다.

video react element

  1. styled component를 사용한 UI 생성

    • Container
      1. 배치 : 정 가운데로 배치
      2. 쌓임순서 : 수직 방향으로 쌓아서, 비디오 -> X 버튼 순으로 쌓이도록 설정
      3. 크기 : 전체 사용

      export const Container = styled.div`
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 100%; /* App.styled.js 의 Container가 main tag이므로 참고 */
        height: 100vh; /* App.styled.js 의 Container 참고 */
      `;
      	
      
    • HomContainer
      1. 크기 : Continer 전체 사용

      export const HomeContainer = styled.div`
        width: 100%;
        height: 100%;
      `;
      
    • Iframe

      export const Iframe = styled.iframe`
        width: 100%;
        height: 100%;
        z-index: -1;
        opacity: 0.65;
        border: none;
      
        &::after {
          content: "";
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
        }
      `;
      		`

학습 : Iframe

Iframe : The Inline Frame element
The "iframe" HTML element represents a nested browsing context, embedding another HTML page into the current one.

Iframe은 inline frame의 약자이며,
효과적으로 다른 HTML페이지를 현재 페이지에 포함시킬 때 사용할 수 있다.
따라서, Iframe 요소를 사용하면, 해당 웹 페이지 안에 어떠한 제한 없이 다른 페이지를 불어와서 삽입 할 수 있다.

Iframe 적용하기

  • 랜더링 할 video는 유튜브를 재생하는 것이므로, Iframe 요소를 사용하는 것이 적절하다.

유튜브 embedded

 <iframe
    width="560"
    height="315"
    src="https://www.youtube.com/embed/k_3E2y5l_rw"
    /* src="https://www.youtube.com/embed/{videoID}?option" */
    title="YouTube video player"
    frameborder="0"
    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
    allowfullscreen
  ></iframe>;

Iframe 컴포넌트에 유튜브 연결하기

  1. axios 인스턴스(src > api > axios.js > fetchData() )를 통해 전달 받은 랜덤한 영화 데이터의 key를 확인한다.
  2. movie state에 axios 인스턴스의 리턴 값이 관리 된다.
  3. 따라서, 콘솔 확인 결과, key 값은 movie.videos.results[0].key를 통해 확인할 수 있다.
 if (isClicked) {
    console.log(isClicked);
    return (
      <>
        <Container>
          <HomeContainer>
            <Iframe
              src={`https://www.youtube.com/embed/
				${movie.videos.results[0].key}?
				controls=0&autoplay=1&loop=1&mute=1&playlist=
				${movie.videos.results[0].key}`}
              width="640"
              height="360"
              frameborder="0"
              allow="autoplay; fullscreen"
            ></Iframe>
          </HomeContainer>
        </Container>
        <button onClick={() => setClicked(false)}>X</button>
      </>
    );
  }

profile
목표 지향을 위해 협업하는 개발자

0개의 댓글