React 프로젝트 내에서 YouTube 영상 재생

slppills·2024년 9월 17일
0

TIL

목록 보기
55/69

팀 프로젝트 중 유튜브에서 검색어에 대한 검색 결과를 유튜브 api로 가져와 프로젝트에 유튜브 영상 그대로 뿌려주는 작업을 맡았다. 특정 키워드에 대한 유튜브 검색 결과를 가져오는 것은 YouTube data api로 할 수 있었다.

const getYoutubeVideo = async (keyword) => {
    try {
      const { data } = await axios.get(
        `https://www.googleapis.com/youtube/v3/search?part=snippet&q=${keyword}&type=video&maxResults=1&key=${
          import.meta.env.VITE_YOUTUBE_KEY
        }`
      );
      return data.items;
    } catch (error) {
      throw error;
    }
  };

  const { data, isPending, isError } = useQuery({
    queryKey: ["getVideo"],
    queryFn: () => getYoutubeVideo("검색어"),
  });

하지만 YouTube data api만 가지고는 유튜브 검색 결과만 가져올 수 있고 유튜브 영상 자체를 프로젝트에서 재생할 수는 없었다. 그래서 이것에 대하여 찾아보던 중 react-youtube라는 라이브러리를 발견했다. react-youtube는 유튜브에서 제공하고 있는 IFrame Player API를 편하게 쓸 수 있도록 컴포넌트 형태로 만든 것이다.

$ yarn add react-youtube

그래서 라이브러리를 따로 설치한 다음, Youtube 컴포넌트를 불러와서 컴포넌트의 videoId에 YouTube data api에서 받아온 id값을 넣어주면 영상을 재생할 수 있다.

<YouTube videoId={video.id.videoId} opts={opts} onEnd={(e) => e.target.stopVideo(0)} />

YouTube 컴포넌트의 prop 구성

<YouTube
  videoId={string}                  // defaults -> ''
  id={string}                       // defaults -> ''
  className={string}                // defaults -> ''
  iframeClassName={string}          // defaults -> ''
  style={object}                    // defaults -> {}
  title={string}                    // defaults -> ''
  loading={string}                  // defaults -> undefined
  opts={obj}                        // defaults -> {}
  onReady={func}                    // defaults -> noop
  onPlay={func}                     // defaults -> noop
  onPause={func}                    // defaults -> noop
  onEnd={func}                      // defaults -> noop
  onError={func}                    // defaults -> noop
  onStateChange={func}              // defaults -> noop
  onPlaybackRateChange={func}       // defaults -> noop
  onPlaybackQualityChange={func}    // defaults -> noop
/>

https://www.npmjs.com/package/react-youtube

0개의 댓글