Filter Search Results by Keywords — JavaScript & React JS
Doing a small exercise creating monster cards using React components and map method, I thought to write about how to create a function of filtering search results by keywords. It let me use various methods like filter() and map() to create the filter that we use everywhere on the web.
The search results filter looks like the above. I would enter the keywords of the monster’s name, and any monster’s name that includes the keywords entered would be filtered and appear.
Each monster’s data such as name, picture, email, and more are in the JSON file which I fetched and passed it to child components so that each one can be rendered automatically.
class CardList extends Component {
const { monsters, searchInput } = this.props;
const lowercasedSearchInput = searchInput.toLowerCase();
const filteredMonsters = monsters.filter((monster) =>
monster.name.toLowerCase().includes(lowercasedSearchInput));return (
<>
<div className=”card-list”>
{filteredMonsters.map((element, index) => {
return (
<Card
key={index}
cardId={element.id}
cardName={element.name}
cardEmail={element.email}
/>
);
})}
</div>
</>
- CardList component gets the
monsters
andsearchInput
props from the parent component.monsters
is for the JSON data fetched, andsearchInput
is for the value entered by the user (e.target.value
). - We need to convert the words entered by the user to lower cases, as well as the monster’s names that start with capital letters. Here,
toLowerCase()
is used and saved to a variable. monsters
is an array of data that have objects with keys representing each information such as name, email, picture, etc, such as:
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
...
Since we want to filter them by their names, we need to access the key of “name” and its values. To do that, we can use filter()
to access each element of the array, and then call the key of “name” . Then, I changed the name to lower cases and then check if the name includes the lower cased search input.
4. Then, filteredMonsters
is mapped for each element to display on the card component. this map()
takes two parameters, element
and index
. For this exercise, index
is used for the key
attribute as the elements will not be modified. Otherwise, a unique key
is required for each. Note that the filter()
filters the data only when the user enters in the search input. All the data will appear if nothing is entered.