Welcome folks today in this blog post we will be building a youtube search autocomplete
videos using youtube data api
v3 in react.js using functional components. All the full source code of the application is given below.
Live Demo
React.js Youtube Search Videos By Keyword
Get Started
In order to get started we need to create a brand new github repository
as shown below to initialize a new react.js
project
react-youtube-search-videos
A React implementation of youtube search videos app using youtube data api.
And also you can clone
the github repository as shown below
git clone https://github.com/amandeepmittal/react-youtube-search.git
cd react-youtube-search-videos
npm install
npm start
The directory structure will look like this as shown below
Now just go to https://console.developers.google.com/google developers console
and create the api key
for your application as shown below
Now store the above api key
and just replace the api_key
inside the below code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
import debounce from 'lodash.debounce'; import React, { Component } from 'react'; import './App.css'; import SearchBar from './components/SearchBar'; import VideoDetail from './components/VideoDetail'; import VideoList from './components/VideoList'; import YTSearch from 'youtube-api-search'; import Footer from './components/Footer'; const REACT_APP_API_KEY = '#####APIKEY######'; class App extends Component { constructor(props) { super(props); this.state = { videos: [], // holds 5 videos fetched from API selectedVideo: null // selected video is null, default set below ln:28 }; this.videoSearch('reactjs'); // default search term } // function for search term videoSearch(term) { YTSearch( { key: REACT_APP_API_KEY, term: term }, videos => { this.setState({ videos: videos, selectedVideo: videos[0] }); // through states setting the default video } ); } render() { // for consistent ui such that it re-renders after 300ms on search const videoSearch = debounce(term => { this.videoSearch(term); }, 300); return ( <div className="container"> <SearchBar onSearchTermChange={videoSearch} /> <div className="columns"> <VideoDetail video={this.state.selectedVideo} /> <VideoList videos={this.state.videos} onVideoSelect={selectedVideo => { this.setState({ selectedVideo }); }} /> </div> <Footer/> </div> ); } } export default App; |
After this when you start the react.js
application your game will start and the screenshot will look like this