Create a searchable dropdown in React using only basic hooks (useState) — no external libraries like react-select:
✅ Features:
- Search filter while typing
- Click to select from dropdown
- Updates selected item
⚛️ React Code Example
import React, { useState } from "react";
const SearchableDropdown = () => {
const options = ["Apple", "Banana", "Orange", "Mango", "Pineapple", "Grapes"];
const [search, setSearch] = useState("");
const [selected, setSelected] = useState("");
const [showDropdown, setShowDropdown] = useState(false);
const filteredOptions = options.filter((option) =>
option.toLowerCase().includes(search.toLowerCase())
);
const handleSelect = (option) => {
setSelected(option);
setSearch("");
setShowDropdown(false);
};
return (
<div style={{ width: 250, margin: "40px auto", position: "relative" }}>
<input
type="text"
placeholder="Search or select"
value={search || selected}
onChange={(e) => {
setSearch(e.target.value);
setShowDropdown(true);
}}
onClick={() => setShowDropdown(!showDropdown)}
style={{ width: "100%", padding: 8, borderRadius: 4 }}
/>
{showDropdown && (
<ul
style={{
listStyle: "none",
margin: 0,
padding: 0,
border: "1px solid #ccc",
borderRadius: 4,
position: "absolute",
width: "100%",
maxHeight: 150,
overflowY: "auto",
backgroundColor: "#fff",
zIndex: 1
}}
>
{filteredOptions.length > 0 ? (
filteredOptions.map((option, index) => (
<li
key={index}
onClick={() => handleSelect(option)}
style={{
padding: 8,
cursor: "pointer",
borderBottom: "1px solid #eee"
}}
>
{option}
</li>
))
) : (
<li style={{ padding: 8 }}>No match found</li>
)}
</ul>
)}
</div>
);
};
export default SearchableDropdown;
🧠 How It Works:
- Input box shows selected item or current search term.
- Filtered options update as the user types.
- Clicking on an item sets it as selected.
- Simple styling using inline CSS for demo.
🖼️ Visual Output:
+------------------------+
| 🍍 Search or select |
+------------------------+
| Apple |
| Banana |
| Grapes |
| ... |