Skip to content

Instantly share code, notes, and snippets.

@karega
Created June 9, 2025 19:09
Show Gist options
  • Save karega/8e3e7af5ad58afa62f49b5f89a4c1a20 to your computer and use it in GitHub Desktop.
Save karega/8e3e7af5ad58afa62f49b5f89a4c1a20 to your computer and use it in GitHub Desktop.
React TypeAhead
// FuseTypeahead.jsx
import React, { useState, useMemo, useCallback } from 'react';
import Fuse from 'fuse.js';
import debounce from 'lodash.debounce';
// Import or define your user data (shortened here)
const users = [
{
name: "Elnora Zimmerman",
email: "elnora_zimmerman@intrawear.cbn",
title: "Something",
user_id: "684729b3c7a20d7083cf2f52",
},
{
name: "Alexandra Daniel",
email: "alexandra_daniel@cogentry.be",
title: "Something",
user_id: "684729b39dca2e8b84ee3feb",
},
// ... include the rest of your dataset here ...
];
const fuse = new Fuse(users, {
keys: ['name', 'email', 'user_id'],
threshold: 0.3, // fuzzy match
ignoreLocation: true,
minMatchCharLength: 1,
isCaseSensitive: false,
});
export default function FuseTypeahead() {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
// Debounced search handler
const search = useCallback(
debounce((q) => {
if (!q) return setResults([]);
const matches = fuse.search(q).slice(0, 10).map(result => result.item);
setResults(matches);
}, 200),
[]
);
const handleChange = (e) => {
const val = e.target.value;
setQuery(val);
search(val);
};
return (
<div style={{ maxWidth: 400, margin: '2rem auto', fontFamily: 'Arial, sans-serif' }}>
<input
type="text"
value={query}
onChange={handleChange}
placeholder="Search users..."
style={{ width: '100%', padding: '8px', fontSize: '16px' }}
/>
{results.length > 0 && (
<ul style={{ listStyle: 'none', padding: 0, marginTop: 10, border: '1px solid #ccc' }}>
{results.map((user, i) => (
<li
key={user.user_id}
style={{
padding: '10px',
borderBottom: '1px solid #eee',
cursor: 'pointer',
backgroundColor: i % 2 === 0 ? '#fafafa' : '#fff',
}}
onClick={() => {
setQuery(user.name);
setResults([]);
}}
>
<div><strong>{user.name}</strong></div>
<div style={{ fontSize: '12px', color: '#555' }}>{user.email}</div>
<div style={{ fontSize: '12px', color: '#aaa' }}>{user.user_id}</div>
</li>
))}
</ul>
)}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment