Searchable List
Build a searchable list where the user can type in a search box and filter items in real time. The search must be case-insensitive and should match any part of the item text. If no items match the search, display a message like "No results found."
Input items: ["React", "Redux", "TypeScript", "TanStack Query"]
User actions:
1. Type: "re" β show: ["React", "Redux"]
2. Type: "ta" β show: ["TanStack Query"]
3. Type: "vue" β show: [] and display "No results found."
import React, { useState, ChangeEvent } from 'react';
type SearchableListProps = {
items: string[];
};
export default function SearchableList({ items }: SearchableListProps) {
const [query, setQuery] = useState('');
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
setQuery(event.target.value);
};
const normalizedQuery = query.toLowerCase();
const filteredItems = items.filter((item) =>
item.toLowerCase().includes(normalizedQuery)
);
return (
<div>
<h2>Searchable List</h2>
<input
type="text"
placeholder="Type to search..."
value={query}
onChange={handleChange}
/>
{filteredItems.length === 0 ? (
<p>No results found.</p>
) : (
<ul>
{filteredItems.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
)}
</div>
);
}