YTSearch in React: How to Create a Search Feature for YouTube API

Laina Karosic
3 min readMay 31, 2020

--

Building a search function to use alongside YouTube API

Once you have your YouTube API key, you’ll likely want to implement a search function so users can start searching for videos. This articles shows you how to implement TYSearch in your React app in a few simple steps.

1. Install youtube-api-search

In your project directory, you’ll first want to install youtub-api-search like so:

 # npm install youtube-api-search

2. Import YTSearch in your app

After installing, you’ll need to import it in your app like so:

Importing YTSearch in your React app

3. Build a Function to Search

We will call our function videoSearch. We will have it accept a search term as an argument:

videoSearch = (term) => {}

This function is going to make use of the YTSearch function that we installed and imported in this file. To do this, we will call YTSearch within this function, and this will accept an object and a callback that returns videos:

videoSearch = (term) => {
YTSearch({}, (videos) => {
})
}

YTSearch will take two parameters in the object: a key and a term:

videoSearch = (term) => {
YTSearch({key: API_KEY, term: term}, (videos) => {
//do something with videos!
})
}

Note that I have API_KEY defined as a variable elsewhere in my code to make it cleaner:

With this code so far, the function is taking your API key and search term, and returning an array of video objects. To be sure it’s working properly, you can console.log(videos) within the function.

From here, you have a ton of options of what you can do next. You might want to create an event listener, such as a Search button that when clicked will run the videoSearch function. I chose to update my state to be the last-searched videos. I also had a larger div on my app with a display video, and chose to take the first video search result from that array (at index 0) and assign it to my displayVideo:

With just a little code so far, you know have the basic tools to begin implementing YTSearch in your app to use as you wish! Happy Coding!

--

--