logo
logo

Search Filter

Medium

Search Filter

Medium

In this exercise, you are tasked with creating a simple Search Filter component that allows users to filter a list of items based on their search input.

Expectations:

  • Create an input field for users to type in their search query

  • Display the list of items and filter them based on the user's search input

  • Use the
    useState
    hook to manage the search input state

Console
Submit
Solution
00:00

Solution Walkthrough for Search Filter

Filtering Items Based on Search Input:

The core functionality of the SearchFilter component is to filter a list of items based on the user's search input. To achieve this, we create a new constant
filteredItems
that filters the original
items
array using the
Array.prototype.filter()
method. We check if each item in the array includes the search term, ignoring case:
const filteredItems = items.filter(item =>
  item.toLowerCase().includes(search.toLowerCase())
);

This approach efficiently filters the list of items based on the user's search input, allowing us to display only the items that match the search criteria.

Rendering Filtered Items:

After filtering the list, we need to render the filtered items within the component. We use the
Array.prototype.map()
method to iterate through the
filteredItems
array and create a list item for each element. This way, we dynamically display the filtered list of items:
<ul>
  {filteredItems.map((item, index) => (
    <li key={index}>{item}</li>
  ))}
</ul>

SearchFilter Component:

The final
SearchFilter
component combines the concepts of controlled components and state management with the filtering functionality to create a responsive search experience for users. As the user types in the search input, the list of items is updated in real-time, reflecting the filtered results based on the user's input.