How to Build a Custom Autocomplete Component in React
Libraries like Downshift or react-select are great, but sometimes you just need a small, fully controlled autocomplete. Here's one in about 40 lines, with keyboard support.
What we're building
- Type to filter a list of suggestions
- Arrow keys to move, Enter to select, Escape to close
- No dependencies
1. Filter as the user types
Keep three pieces of state: the input value, whether the list is open, and the highlighted index.
import { useState } from "react";
export default function Autocomplete({ options, onSelect }) {
const [query, setQuery] = useState("");
const [open, setOpen] = useState(false);
const [active, setActive] = useState(0);
const results = options.filter((o) =>
o.toLowerCase().includes(query.toLowerCase())
);
Filtering is derived state. Compute it during render instead of storing it, so it never goes stale.
2. Handle the keyboard
const choose = (value) => {
setQuery(value);
setOpen(false);
onSelect?.(value);
};
const onKeyDown = (e) => {
if (e.key === "ArrowDown") {
e.preventDefault();
setActive((i) => Math.min(i + 1, results.length - 1));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive((i) => Math.max(i - 1, 0));
} else if (e.key === "Enter" && results[active]) {
choose(results[active]);
} else if (e.key === "Escape") {
setOpen(false);
}
};
3. Render the input and list
return (
<div style={{ position: "relative", width: 240 }}>
<input
value={query}
placeholder="Search a fruit..."
role="combobox"
aria-expanded={open}
onChange={(e) => {
setQuery(e.target.value);
setActive(0);
setOpen(true);
}}
onKeyDown={onKeyDown}
onBlur={() => setOpen(false)}
/>
{open && results.length > 0 && (
<ul role="listbox" style={{ position: "absolute", margin: 0, padding: 0, listStyle: "none" }}>
{results.map((item, i) => (
<li
key={item}
role="option"
aria-selected={i === active}
style={{ background: i === active ? "#eee" : "white" }}
onMouseDown={() => choose(item)}
>
{item}
</li>
))}
</ul>
)}
</div>
);
}
Note onMouseDown on the items, not onClick. The input's onBlur fires before a click lands, which would close the list and swallow the selection. mousedown fires first.
4. Use it
<Autocomplete
options={["Apple", "Apricot", "Banana", "Blueberry", "Cherry"]}
onSelect={(v) => console.log("Picked:", v)}
/>
Typing ap shows Apple and Apricot. Press ArrowDown, then Enter, and the input fills with your pick.
Where to go next
The basic version works. Here are four upgrades worth adding, each in a few lines.
1. Async data
When options come from an API, store results in state and fetch with a debounce so you don't fire a request on every keystroke.
useEffect(() => {
if (!query) return setResults([]);
const id = setTimeout(async () => {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
setResults(await res.json());
}, 300);
return () => clearTimeout(id);
}, [query]);
The cleanup function cancels the previous timer, so only the last keystroke in a 300ms window triggers a request.
2. Highlight the match
Wrap the matched part of each suggestion in <mark> so users see why it appeared.
function Highlight({ text, query }) {
const i = text.toLowerCase().indexOf(query.toLowerCase());
if (!query || i === -1) return text;
return (
<>
{text.slice(0, i)}
<mark>{text.slice(i, i + query.length)}</mark>
{text.slice(i + query.length)}
</>
);
}
// inside the list item
<Highlight text={item} query={query} />
Typing ap renders Apple and Apricot with the matching letters highlighted.
3. Make it screen-reader friendly
Screen readers don't see the visual highlight. Give each option an id and point the input at the active one.
<input aria-controls="suggestions" aria-activedescendant={`opt-${active}`} />
<ul id="suggestions" role="listbox">
<li id={`opt-${i}`} role="option" aria-selected={i === active}>
{item}
</li>
</ul>
4. Keep it fast with large lists
Memoize the filter so it only reruns when the query or options change.
const results = useMemo(
() => options.filter((o) => o.toLowerCase().includes(query.toLowerCase())),
[options, query]
);
For thousands of options, render only the visible rows with a virtualization library like react-window.
Wrap up
You now have a dependency-free autocomplete with filtering, keyboard navigation and a clean selection flow. Start with the basic version, then add async data or accessibility as your use case demands.
About the author
Push karo khush raho ;)
Comments
Join the discussionNo comments yet. Be the first to comment.