Fetch YouTube Playlist in Reactjs
A quick guide on how to fetch and display a YouTube playlist in Reactjs using the YouTube Data API v3
Integrating YouTube playlists into your React application can provide easy access to curated video content. Whether you're building a video gallery or learning platform, or you just want to showcase your favorite videos, this step-by-step guide will help you seamlessly incorporate YouTube playlists into your React app using the YouTube Data API.
Step 1. Create a Google Console Project
Visit Google Developer Console to create a new project. If you don't have a Google Console account, create one by signing into your Gmail account. Once authenticated, click on the "Select Project" button, a modal should be displayed to select your project, simply click "New Project" to create a fresh one.
Give the project a preferred name and optionally choose an organization to associate the project with. Once completed, hit "Create"
Step 2. Get API Key
Next, you need to generate an API key to grant access to the project. Visit Credentials to obtain an authorization credential for fetching using the API, click the "Create Credentials" button and select "API Key" from the dropdown menu.
Follow the prompts to successfully create your keys and then copy it. I advise you restrict the keys to the particular URL the keys will be used to prevent unauthorized access. Next, click the Enable API Services
link on the left sidebar, search for YouTube Data API v3 and enable the status.
With this, your API is ready to be used in production.
Step 3. Fetch Playlist Videos
To test the API, use the YouTube API documentation playground. Here's how:
- Visit the YouTube API documentation .
- Click the
API
button at the top right corner to open the playground widget. - Set the parameter
part
tocontentDetails
. - Paste the
playlistId
into the appropriate field.
To find the playlist ID, copy it from the playlist URL. For example, in the URL https://youtube.com/watch?v=WINbDH7w9Ag&list=PLs1-UdHIwbo5fx0MbqyoEG5qDqzZjK9WC , the ID is PLs1-UdHIwbo5fx0MbqyoEG5qDqzZjK9WC
.
Once added, click the Execute button to fetch the playlist videos. If successful, it should return a list of public videos in the playlist like so:
Now you know it's working, it's time to display the videos in your application. Run the below command to quickly bootstrap a React application if you don't have any.
Bootstrap a new React application
npm create vite@latest youtube-project -- --template react-ts
Step 4. Display YouTube Playlist
Fetching the videos is simple, here's the code for doing this:
src/api.ts
const API_KEY = "XXXXXXXXXXXXXXXXXXXX";
const PLAYLIST_ID = "PLs1-UdHIwbo5fx0MbqyoEG5qDqzZjK9WC";
export async function getPlaylist() {
const request = await fetch(
`https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=25&playlistId=${PLAYLIST_ID}&key=${API_KEY}`
).then((res) => {
if (!res.ok) {
console.log(res.statusText);
throw new Error("Failed to fetch data");
}
const data = res.json();
return data;
});
return request.items;
}
Substitute the API_KEY
and PLAYLIST_ID
with your details. To display the YouTube videos, you can utilize the HTML iframe
element. Here's the component:
src/components/YoutubeWidget.tsx
import { useEffect, useState } from "react";
import { getPlaylist } from "../api";
type YoutubeType = {
contentDetails: {
videoId: string;
videoPublishedAt: string;
};
snippet: {
title: string;
publishedAt: string;
playlistId: string;
};
};
const iframeStyle = {
borderRadius: "10px",
border: 0,
backgroundColor: "#eeeeee",
aspectRatio: "16/9",
};
export default function YoutubeWidget() {
const [data, setData] = useState<YoutubeType[] | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const videos = await getPlaylist();
setData(videos);
} catch (error) {
setError(true);
} finally {
setLoading(false);
}
};
fetchData();
}, []);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error loading video</div>;
const videos = data?.map((video) => video);
return (
<>
{videos?.map((video) => (
<iframe
key={video.contentDetails.videoId}
width="100%"
height="100%"
src={`https://youtube.com/embed/${video.contentDetails.videoId}?list=${video.snippet.playlistId}`}
title={video.snippet.title}
style={iframeStyle}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerPolicy="strict-origin-when-cross-origin"
allowFullScreen
></iframe>
))}
</>
);
}
Now call this component inside the App component to display the embeds.
src/app.tsx
import YoutubeWidget from "./components/YoutubeWidget";
export default function App() {
return (
<main className="container">
<h1>Youtube Videos</h1>
<section className="video-container">
<YoutubeWidget />
</section>
</main>
);
}
Here's the final output
Reference
- RadBrad. (2019). The Walking Dead Game The Final Season (Season 4) Gameplay . YouTube.
- YouTube API Documentation
- Google Developer Console
Comments