Search Bar in React JS in Six Simple Steps

Search Bar in React JS in Six Simple Steps

So you want to make a search bar in React JS. Cool!

You may have seen something like .indexOf() but today I?m going to show you a simple way to accomplish this goal for your app.

Image for post

React JS Logo

Step 1: Decide where you want to display your search bar.

Which component do you want to render your JSX and display to the screen?

For this example, I?d like to render the search bar in my Pet List component, which holds my collection of pets (pets array) that is in State. This Pet List component receives the Pets from its parent component, the Pet Container, where the State is passed down as props to the Pet List component.

To create the search bar, we write the following html inside JSX to render:

First create a JSX fragment tag to hold your element. Next, write an HTML label tag. Include an htmlFor attribute.

Then use an HTML input tag with type attribute set to ?text?. We want to make a controlled input, so explicitly provide the value attribute and assign it to the props passed down from the parent component for the input value. In the next step, we will provide this key/value to our State in the parent component and pass it down to use here.

Finally, create an onChange attribute to handle the Search. We will create this function in the parent container and pass it down as props to use here when the input value in the search bar changes based on user input.

Image for post

Step 2. Know where you?re holding State for that component.

Will your search bar be in the same component in which your state lives? Or will your state be in the parent?

If your Search bar renders in a child component, you?ll still need to have an onChange event handler for the state of the inputs. Where will that live? If it?s in your parent, you?ll send the function down as props.

Step 3: Create an input value for your search field in your State object.

For example, I set the input value to an empty string in State in the parent component:

Image for post

Step 4. Create the method to handle the on change event for your search bar input.

The handle on change method for your search bar input. I recommend using ES6 Arrow functions to be sure that you?ll bind the value of this. Since this on change handler method will be defined in the parent and will be responsible for taking in the event object, and setting state in the parent, we need to be sure it?s keeping its value of ?this? for this.setState() method to be used properly.

Inside the function body, we call another function on this (the parent component) Set State, which will enable us to update the state, thus not directly mutating it (never directly mutate state!).

In the function body of set state, we set the key of input value which is defined in our current state to receive the value of the event target that we passed in as an argument to the handle on change. The event target value is passed up from the child component, who invokes this function each time a change is detected in the input field of the search bar by accessing the callback since it is passed down as props from the parent.

Hot tip! Remember to console log! you can be sure you?re making the proper connections from the parent to the child and receiving the value of your event target on the input.

Image for post

Step 5: Pass down the props and test along the way!

To test at this point, make sure you pass down the state as props for input value and also the handle on change function for the input field of the search bar as props to the child component, like so:

Image for post

Step 6: Create a Search Method and connect it!

For this, we?re gonna use Filter & Includes methods for this, not Index Of.

Image for post

And now, for the real fun. Actually searching!

We?re going to create a variable named Filtered Pets, whose return value will be an array of filtered pets, filtered based on the input value key from the state that?s been updated by the on change handler that?s invoked in the input field of the search bar.

MDN explains that ?The filter() method creates a new array with all elements that pass the test implemented by the provided function.?

We?ll be sure to define this variable after the render lifecycle method in our Pet Container class component and before the return statement. We?ll use the variable inside the return method to pass down as an argument to our callback function for the sort handler, which we?re passing down as props to the Pet List child component. This is so we can have the array of pets in state of the parent (pet container) available as props to the child (Pet List) and so this array will be both sorted and filtered for search, depending on if that?s so.

Filtered Pets will call a function .filter() on the array of pets that?s in state, filtering through the array and for each pet in the array, checking a condition. The filter method checks a condition and returns a boolean.

For each pet, we want to return that pet in the array, call the to lower case method to account for capitalization, then call the includes method, passing in the state of the input value key event target, in other words, the event target value we got from the on change handler in the input field of our search bar. Include method works on arrays and array like objects.

According to MDN, includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

And from Geeks for Geeks:

In JavaScript, includes() method determines whether a string contains the given characters within it or not. This method returns true if the string contains the characters, otherwise, it returns false.

And from W3School: Includes: Return Value: A Boolean. Returns true if the string contains the value, otherwise it returns false

We must call the to lower case method there as well, again to account for capitalization, this time from the user?s input.

The condition we are filtering for is to check if any of the array of pets in state includes the input in order entered into the search bar and if so, returning that pet into a new array if it meets the condition. So the return value will be a new array of only pets which meet the condition of including the search value input.

Since we set this callback function to a variable, we have access to the return value of the function (the array of filtered pets) which we can then call to use and pass into another function (sort!) as an argument. Then we can pass both together as props to the child component.

We want to account for this because we want our user to be able to both sort and search through our collection of pets. So the pets prop that we pass to the Pet List component will contain the pets in state that have been sorted and searched, if so!

Image for post

Collections are fun! And even more so when you can search through them.

If you?re curious about how the includes method works under the hood, from an algorithmic perspective, I am, too. MDN says :

Computed index is less than 0

If fromIndex is negative, the computed index is calculated to be used as a position in the array at which to begin searching for valueToFind. If the computed index is less or equal than -1 * array.length, the entire array will be searched.

// array length is 3// fromIndex is -100// computed index is 3 + (-100) = -97var arr = [‘a’, ‘b’, ‘c’];arr.includes(‘a’, -100); // truearr.includes(‘b’, -100); // truearr.includes(‘c’, -100); // truearr.includes(‘a’, -2); // false

includes() used as a generic method

includes() method is intentionally generic. It does not require this value to be an Array object, so it can be applied to other kinds of objects (e.g. array-like objects). The example below illustrates includes() method called on the function’s arguments object.

(function() { console.log(.includes.call(arguments, ‘a’)); // true console.log(.includes.call(arguments, ‘d’)); // false})(‘a’,’b’,’c’);

Includes is implemented differently in different JS engines. So I?m not sure what algorithm it uses to search strings, if it?s binary or linear and how it works, but please let me know if you find out.

And here?s what we built, in action. I built this Pet Adoption App, Doggo-doption, with my amazing cohort wifey, Darya Tanriverdi, at The Flatiron School.

Image for postSearch bar feature in React JS web application built by Rene Cruz & Derya Tanriverdi at The Flatiron School.

Resources:

Array.prototype.includes()

The includes() method determines whether an array includes a certain value among its entries, returning true or false?

developer.mozilla.org

Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function?

developer.mozilla.org

JavaScript | String includes() Method – GeeksforGeeks

In JavaScript, includes() method determines whether a string contains the given characters within it or not. This?

www.geeksforgeeks.org

31