There are many ways we can create a search bar, but in this blog, I will show you how I created my search bar for my youtube clone project using a youtube API. First we have to understand, what are search bars? It’s pretty simple, a search bar contains an input field with a submit button to search what we want to search. In react, we want our search bar to be dynamic and initialize state in order to have a controllable form. In my following examples, we will walkthrough this component and I will explain what are the roles of each function created.
**To follow along, fork this repository on github
Let’s Get Started!
Step 1- Creating a SearchBar Class Component
Let’s start by creating a class component. Make sure you invoke the rener method and a return. Also, make sure you export default, that way we can use it in other components. Our search should have a label and an input field type of text. This should be similiar to the code below:
Step 2- Initializing State
When we initalizie our state in our SearchBar component, we can either initialize by using a constructer, in this case we can also initalize state just like the code below: We are going to set term to an empty string.
Step 3- Creating a onChange Event
In this step we have to pass an onChange Event to our input field. We would have to create a function that will change the state of the term with
setState . First we have to create a function, let’s call it
onInputChange : This code should look like below:
We passed in the event as an argument. We used setState in order to change the change of the term to the event.target.value, which would be what the use inputs on the input field. The second step is that we have to invoke this function to a onChange event for the input field, and we also have to invoke a value attribute to make this a controllable form. Let’s take a look below:
Step 4- Creating a onSubmit Event
Now, we also have to create a function of when the form submits we will pass in a callback from the parent component, which would be passed down from props. This is the parent component:
As you can see, we are passing doe the onTermSubmit function as a prop to our SearchBar. Let’s create our
onFormSubmit function. Take a look below:
onFormSubmit will preventDefault and not relaod the page, and will call the onFormSubmit function that was passed down as a prop from the App (parent) component. Now we have to invoke the onFormSubmit function to our onSubmit event for our form. Let’s take a look:
Check out this video to learn how to implement a search bar