React | Build TypeHead Component

A Typeahead component is used to provide autocomplete suggestions as the user types into an input field.

Here’s a simple example of a Typeahead component in React using React Hooks:

import React from 'react';
import './style.css';
import Typeahead from './typehead';

const App = () => {
const suggestions = ['Apple', 'Banana', 'Cherry', 'Date', 'Fig', 'Grapes'];

return (
<div>
<h1>Typeahead Example</h1>
<Typeahead suggestions={suggestions} />
</div>
);
};

export default App;

TypeHead Component:

// Typeahead.js
import React, { useState } from 'react';

const Typeahead = ({ suggestions }) => {
const [inputValue, setInputValue] = useState('');
const [filteredSuggestions, setFilteredSuggestions] = useState([]);
const [showSuggestions, setShowSuggestions] = useState(false);

const handleInputChange = (e) => {
const value = e.target.value;
setInputValue(value);

// Filter suggestions based on the input value
const filtered = suggestions.filter((suggestion) =>
suggestion.toLowerCase().includes(value.toLowerCase())
);

setFilteredSuggestions(filtered);
setShowSuggestions(true);
};

const handleSelectSuggestion = (value) => {
setInputValue(value);
setShowSuggestions(false);
};

const handleBlur = () => {
// Hide suggestions when input field loses focus
setTimeout(() => {
setShowSuggestions(false);
}, 100);
};

return (
<div className="typeahead">
<input
type="text"
value={inputValue}
onChange={handleInputChange}
onBlur={handleBlur}
placeholder="Type something..."
/>

<ul className="suggestions">
{filteredSuggestions.map((suggestion, index) => (
<li key={index} onClick={() => handleSelectSuggestion(suggestion)}>
{suggestion}
</li>
))}
</ul>
</div>
);
};

export default Typeahead;

Thanks for reading

I know there would always be something to improve. Please feel free to share your thoughts

--

--