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…

--

--

Sonika | @Walmart | Frontend Developer | 11 Years
Sonika | @Walmart | Frontend Developer | 11 Years

No responses yet