Adding a Search Bar!
- Chuck Curtis
- Oct 16, 2019
- 2 min read
I want to add a search bar to the app so that the user can search by name and location. To start I add a new input to the Groups component. In order for the input to display the text that's being typed I need to add a new state property and decide that searchValue is an appropriate name. Input elements have a value prop and an onChange prop. I set the input value to {searchValue} from the state, and I will need to write a new function for onChange. I name the new function onSearch.
I haven't created a search bar like this before, so I play around with different ways of writing onSearch. onSearch gets an event parameter from the input, and the value can be accessed using event.target.value. Since I'm searching through the groups array in the state, I bring the array into the function as well. I don't want change the groups array, I only want the list to update when the user types into the search bar. I want to do a live search so there's no submit button. As soon as the user starts typing the list updates.
I define a new variable called searchGroups, which I also add to the component state. This new variable is a new array defined by filtering the groups array based on the input value. Since I want to search by group name (aka 'sport') I access the key 'sport' in each object in the groups array, and if the sport includes the search value, I return the object. Since I also want to search by city or state, I also include the 'city' and 'state' keys in the function. I add the toLowerCase() method to each part of the function since I don't want the search to be case sensitive.

The final step in onSearch is to update the component state for searchGroups (the new array of groups) and searchValue (the value of the input).
To display the searchGroups array instead of the groups array I'll use a ternary in the return value of the component. If searchGroups has a length (length > 0) then the component will map through searchGroups. If searchGroups does not have a length, then the component will map through the groups array.

Adding the search bar is really satisfying, and it works well! The search bar looks for a match in the group name, city, or state so users can look for a group nearby, or look for a specific sport or activity and get instant results. In the following screen shots I search for 'b' and the all the groups with a 'b' in the title, city, or state show, and then I add an 'i' and only the Bike group appears. I also search 'NH' and 'gilford' respectively and the search bar is acting like I expected it would!
One bug that I'm working out is that when a search input doesn't match any groups, the entire groups list appears. Ideally, I would display a message like 'No Groups Found!' but I'm still working on the best way to accomplish this, check back again later for an update!
Comments