
Building fast, interactive web applications is the goal of every developer, and a dynamic search bar that filters a list in real-time is a classic example of this.
It showcases core React principles: state management, event handling, and controlled components.
Let’s dive into the code for a simple but powerful React component, FilterableList, and understand how it brings data to life.
๐๏ธ The Component Structure
Our component is a standard functional component that leverages the useState Hook to manage the data that changes based on user input.
import React, { useState } from 'react';
import './FilterableList.css';
const initialItems = [
'Apple',
'Banana',
'Cherry',
'Date',
'Elderberry',
// ... more fruits
];
function FilterableList() {
// ... logic and JSX ...
}
The Unchanging Truth: initialItems
The initialItems array is the source of truth. This constant array holds the complete, original list of data. It is crucial because we always want to filter from this original list, ensuring that when the user deletes a search query, the full list reappears.
โจ State Management with useState
For this component to be dynamic, we need to track two essential pieces of information that change over time:
-
searchTerm: What the user has currently typed into the input box. -
filteredItems: The subset ofinitialItemsthat matches the current search query.
const [searchTerm, setSearchTerm] = useState('');
const [filteredItems, setFilteredItems] = useState(initialItems);
-
searchTermstarts as an empty string (''). -
filteredItemsstarts with the entireinitialItemsarray, so the full list is visible when the component first loads.
๐ The Engine: handleSearchChange
This function is the heart of the filtering logic. It executes every time the user types a character.
const handleSearchChange = (event) => {
const query = event.target.value.toLowerCase();
// 1. Update the Input's Value (State 1)
setSearchTerm(query);
// 2. Perform the Filtering Calculation
const newFilteredItems = initialItems.filter((item) =>
item.toLowerCase().includes(query)
);
// 3. Update the Displayed List (State 2)
setFilteredItems(newFilteredItems);
};
Step-by-Step Breakdown:
-
Capture and Standardize Query:
-
const query = event.target.value.toLowerCase(); -
We grab the input text (
event.target.value) and immediately convert it to lowercase. This ensures case-insensitive searchingโa huge win for user experience.
-
-
Update the Search Term State:
-
setSearchTerm(query); -
This updates the
searchTermstate, which is linked to the input’svalueprop. This step makes the input a controlled component and triggers React to re-render the component.
-
-
Filter the List (The Magic):
-
initialItems.filter(...)creates a new array (newFilteredItems) containing only the items where the item’s lowercase name includes thequerystring. This is a non-destructive operation, leavinginitialItemsuntouched.
-
-
Update the Filtered List State:
-
setFilteredItems(newFilteredItems); -
This is the second critical state update. By passing the newly calculated array, we tell React to update the
filteredItemsstate. This also triggers a re-render where the JSX will read this new, shorter array.
-
๐ผ๏ธ The Display: JSX and Conditional Rendering
The return statement is where the state meets the screen.
return (
<div className="filterable-list-container">
{/* ... Input Element ... */}
<ul className="item-list">
{filteredItems.length > 0 ? (
filteredItems.map((item, index) => (
<li key={index} className="list-item">{item}</li>
))
) : (
<li className="no-results">No results found.</li>
)}
</ul>
</div>
);
The Power of Data Binding:
-
Input Control: The
<input>has thevalue={searchTerm}prop. BecausesearchTermis state, the input is entirely controlled by React. TheonChangeprop ensures the state is updated on every keystroke. -
List Rendering: The
<ul>element uses a ternary operator (? :) for conditional rendering.-
If
filteredItemsis not empty: We use themap()method on the state variablefilteredItemsto dynamically generate an<li>element for every match. -
If
filteredItemsis empty: We display a simple message: “No results found.”
-
This entire system beautifully demonstrates the React Data Flow: User action updates state, state change triggers re-render, and the component’s JSX reflects the new state, updating the UI.
Useful links below:
Let me & my team build you a money making website/blog for your businessย https://bit.ly/tnrwebsite_service
Get Bluehost hosting for as little as $1.99/month (save 75%)โฆhttps://bit.ly/3C1fZd2
Best email marketing automation solution on the market!ย http://www.aweber.com/?373860
Build high converting sales funnels with a few simple clicks of your mouse!ย https://bit.ly/484YV29
Join my Patreon for one-on-one coaching and help with your codingโฆhttps://www.patreon.com/c/TyronneRatcliff
Buy me a coffeeย https://buymeacoffee.com/tyronneratcliff



