Skip to content

Instantly share code, notes, and snippets.

@zavier-sanders
Created January 3, 2017 19:22
Show Gist options
  • Save zavier-sanders/5946b9f788e296b20944c620a72c12e1 to your computer and use it in GitHub Desktop.
Save zavier-sanders/5946b9f788e296b20944c620a72c12e1 to your computer and use it in GitHub Desktop.
JavaScript code to render a YouTube Client, with instantaneous search.
import _ from 'lodash';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
//import components needed for the app
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';
import './index.css';
const API_KEY = 'AIzaSyC1TbfA9O2spN4MRVmDowEJfoVFcOwbwJc';
class App extends Component {
constructor(props) {
super(props);
//store the information we want to render in the state of the component
this.state = {
videos: [],
selectedVideo: null
};
//pass the videoSearch function with a default search term 'javascript'
this.videoSearch('javascript');
}
//call Youtube api passing in api key and search term
videoSearch(term) {
YTSearch({key: API_KEY, term: term}, (videos) => {
console.log(videos);
this.setState({
videos: videos,
selectedVideo: videos[0]
});
});
}
render() {
//throttle api calls using lodash's debounce function
const videoSearch = _.debounce((term) => { this.videoSearch(term) }, 300);
return (
<div>
//pass the videoSearch function as a prop to the Search component
<SearchBar onSearchTermChange={videoSearch} />
<br/>
//pass the selected video from state as a prop to the Video component
<VideoDetail video={this.state.selectedVideo} />
//pass selectedVideo function and video state as props to VideoList
<VideoList
onVideoSelect={selectedVideo => this.setState({selectedVideo}) }
videos={this.state.videos} />
</div>
);
}
}
ReactDOM.render( <App /> , document.querySelector('#root'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment