React.js Youtube Data API V3 Video Search Example Using Axios Full Tutorial For Beginners (2020)

 

Welcome folks today in this blog post we will be building a youtube video search app in react.js using axios and youtube data api v3. All the source code of the video is shown below. A step by step youtube video is also shown below.

 

 

 

 

 

Screenshots

 

 

 

 

 

Get Started

 

In order to get started you need to install these dependencies as follows

npm i axios

Through axios we will be making the http request to the youtube data api v3. So we will get the videos data and display these videos using their respective components.

Now you need to make the app.js file and import react dependency as follows

 

import React from "react";
import "./styles.css";

 

 

Now after that we will making this base app component like this

 

export default class App extends React.Component {

state = {
    videosMetaInfo: [],
    selectedVideoId: null
  };

 render() {
    return (
      <div className="App">
        
      </div>
    );
  }

}

 

 

Make Search Component

 

Now we will be making the search component and in this we will be having the form in which we will be having a simple input field like this

 

 

 

import React from "react";

class Search extends React.Component {
  state = { title: "" };
  onSearchChanged = event => {
    const _title = event.target.value;
    this.setState({ title: _title });
  };
  onSubmit = event => {
    event.preventDefault();
    this.props.onSearch(this.state.title);
  };
  render() {
    return (
      <>
        <form onSubmit={this.onSubmit} className="search-form">
          <div className="form-controls">
            <label>Search</label>
            <input
              id="video-search"
              type="text"
              value={this.state.title}
              onChange={this.onSearchChanged}
              placeholder="Enter Search Keyword"
            />
          </div>
        </form>
      </>
    );
  }
}

export default Search;

 

 

Now we will be including this component inside app.js file like this

 

 

render() {
    return (
      <div className="App">
        <Search onSearch={this.onSearch} />
      </div>
    );
  }

 

 

 

 

 

Now we will submit the form and when we submit the form with the actual keyword and when we hit the enter button this function onSearch function will execute and we will write this function as follows

See also  React.js Wordpress Wysiwyg Rich HTML Text Editor Using Quill Library in Browser Using Javascript Full Project For Beginners

 

 

onSearch = async keyword => {
    const response = await youtubeApi.get("/search", {
      params: {
        q: keyword
      }
    });
    this.setState({
      videosMetaInfo: response.data.items,
      selectedVideoId: response.data.items[0].id.videoId
    });
    console.log(this.state);
  };

 

 

So write here inside this block of code we are writing the async function and inside this we are using a separate component youtubeApi so in this component we will use axios to make the get request to the youtube data api v3

 

 

 

 

api/youtube.js

 

import axios from "axios";
const KEY = "AIzaSyCFkWFFKrwcZtbaCfFehJk6nOkOLb3FUqM";

export default axios.create({
  baseURL: "https://www.googleapis.com/youtube/v3",
  params: {
    part: "snippet",
    maxResults: 5,
    key: KEY
  },
  headers: {}
});

 

 

 

 

 

Making the Videos List Component

 

 

Now inside this section we will be making the Videos List Component. Inside this videos list component we will be displaying four videos inside the form of a list.

 

 

 

 

import React from "react";

import Video from "./Video";

const VideoList = ({ data, onVideoSelected }) => {
  return (
    <div className="video-list">
      <div style={{ padding: "20px 0" }}>
        <h3
          style={{ textAlign: "center", fontSize: "18px", fontWeight: "bold" }}
        >
          Videos List
        </h3>
        <Video data={data} onVideoSelected={onVideoSelected} />
      </div>
    </div>
  );
};

export default VideoList;

 

 

 

Now inside this block of code we are making the individual video component i.e. video.js so inside this video.js component we will pass the data and also pass which video is selected and pass it’s id.

 

 

import React from "react";
import "../styles/_video.css";
function selectVideo(videoIdObj, onVideoSelected) {
  onVideoSelected(videoIdObj.videoId);
}
function getCss(imageurl) {
  const _styles = {
    backgroundImage: `url(${imageurl})`,
    backgroundSize: "cover",
    backgroundPosition: "center center",
    height: "180px",
    position: "relative"
  };
  return _styles;
}
function constructVideoTitles(vidoesData, onVideoSelected) {
  return vidoesData.map(({ snippet, id }, index) => {
    return (
      <div
        className="video"
        key={index}
        onClick={() => selectVideo(id, onVideoSelected)}>
        <div style={getCss(snippet.thumbnails.high.url)} key={index} />
        <p className="title">{snippet.title}</p>
      </div>
    );
  });
}
const Video = ({ data, onVideoSelected }) => {
  return <>{constructVideoTitles(data, onVideoSelected)}</>;
};

export default Video;

 

See also  jsPDF React.js Example to Generate a PDF File in Javascript Full Project For Beginners

 

Now we will include the videoList component inside the app.js like this as shown below.

 

 

<VideoList
          onVideoSelected={this.onVideoSelected}
          data={this.state.videosMetaInfo}
        />

 

 

 

Making the VideoPlayer Component

 

<Videoplayer videoId={this.state.selectedVideoId} />

 

 

In order to use this component we will pass the selectedVideoId of the video which is selected

 

 

import React from "react";

const Videoplayer = ({ videoId }) => {
  if (!videoId) {
    return (
      <p style={{ textAlign: "center", fontSize: "18px", fontWeight: "bold" }}>
        Search for a video
      </p>
    );
  }
  return (
    <div className="video-player">
      <iframe
        title={videoId}
        className="video-iframe"
        src={`https://www.youtube.com/embed/${videoId}`}
      />
    </div>
  );
};

export default Videoplayer;

 

 

App Component Styles

 

 

html {
  height: 100vh;
  font-family: sans-serif;
  box-sizing: border-box;
}

body,
#root,
.App {
  height: 100%;
  margin: 0;
}

.App {
  display: grid;
  grid-template-columns: 70% 1fr;
  grid-template-rows: 70px auto;
}
.search-form {
  border-bottom: 1px solid lightgray;
  display: flex;
  justify-content: flex-start;
  padding: 0 20px;
  align-items: center;
}

.form-controls {
  display: flex;
  flex-grow: 1;
  align-items: center;
  justify-content: space-between;
}
.form-controls input[type="text"] {
  display: flex;
  border: 1px solid lightgray;
  flex-grow: 1;
  padding: 10px;
  border-radius: 4px;
  font-size: 16px;
}
.form-controls input[type="text"]:focus {
  outline: none;
  border-color: gray;
  box-shadow: 0 2px 5px lightgray;
}

.form-controls label {
  display: none;
}

 

 

Video Component Styles

 

 

.video {
  box-shadow: 0 2px 1px lightgray;
  border: 1px solid lightgray;
  border-radius: 2px;
  margin: 20px 0;
}

.video > .title {
  text-align: center;
  padding: 10px;
  margin: 0;
  font-weight: 600;
  font-size: 14px;
}
.video-list {
  border-left: 1px solid lightgray;
  grid-row: span 2;
  padding: 0 20px;
  height: 100%;
  overflow: auto;
}

.video-player .video-iframe {
  width: 100%;
  height: 100%;
}

 

 

 

Leave a Reply