Autocomplete search boxes have become an essential feature in modern web applications. They provide users with instant feedback and suggestions, making searching quicker and more efficient. In this tutorial, we’ll build a simple search autocomplete typeahead component in React.
To start with, let's create our React application using Create React App. If you haven't done this already, you can initialize a new project by running:
npx create-react-app search-autocomplete cd search-autocomplete
Once the application is set up, navigate to the src
directory to begin works on our component.
Let’s create a new component called SearchAutocomplete.js
inside the src
folder:
// src/SearchAutocomplete.js import React, { useState } from 'react'; const SearchAutocomplete = () => { return ( <div> <input type="text" placeholder="Search..." /> {/* Suggestions will go here */} </div> ); }; export default SearchAutocomplete;
Next, we need to manage the input state and the suggestions displayed to the users. We’ll also set up a basic list of suggestions:
// src/SearchAutocomplete.js import React, { useState } from 'react'; const suggestionsList = [ "Apple", "Banana", "Orange", "Mango", "Grapes", "Pineapple", "Strawberry", ]; const SearchAutocomplete = () => { const [query, setQuery] = useState(''); const [suggestions, setSuggestions] = useState([]); return ( <div> <input type="text" value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search..." /> {/* Suggestions will go here */} </div> ); }; export default SearchAutocomplete;
Now let's filter the suggestions based on what the user types in the input field. We'll use the filter
method to generate relevant suggestions:
const filterSuggestions = (query) => { return suggestionsList.filter(suggestion => suggestion.toLowerCase().startsWith(query.toLowerCase()) ); }; const SearchAutocomplete = () => { const [query, setQuery] = useState(''); const [suggestions, setSuggestions] = useState([]); const handleChange = (e) => { const inputValue = e.target.value; setQuery(inputValue); setSuggestions(filterSuggestions(inputValue)); }; return ( <div> <input type="text" value={query} onChange={handleChange} placeholder="Search..." /> {/* Suggestions will go here */} </div> ); };
Let’s add the section to display filtered suggestions below the input field:
return ( <div> <input type="text" value={query} onChange={handleChange} placeholder="Search..." /> {suggestions.length > 0 && ( <ul> {suggestions.map((suggestion, index) => ( <li key={index}>{suggestion}</li> ))} </ul> )} </div> );
Now, let’s add some basic CSS styles to improve the appearance of the input and suggestions list. You can include this in your App.css
or in the same file using styled-components or another CSS-in-JS solution.
input { width: 100%; padding: 10px; margin: 8px 0; box-sizing: border-box; } ul { list-style-type: none; padding: 0; } li { padding: 10px; background-color: #f9f9f9; border: 1px solid #ccc; cursor: pointer; } li:hover { background-color: #ddd; }
Now that we have all pieces in place, let's look at the complete code of our SearchAutocomplete
component:
// src/SearchAutocomplete.js import React, { useState } from 'react'; const suggestionsList = [ "Apple", "Banana", "Orange", "Mango", "Grapes", "Pineapple", "Strawberry", ]; const SearchAutocomplete = () => { const [query, setQuery] = useState(''); const [suggestions, setSuggestions] = useState([]); const handleChange = (e) => { const inputValue = e.target.value; setQuery(inputValue); setSuggestions(filterSuggestions(inputValue)); }; const filterSuggestions = (query) => { return suggestionsList.filter(suggestion => suggestion.toLowerCase().startsWith(query.toLowerCase()) ); }; return ( <div> <input type="text" value={query} onChange={handleChange} placeholder="Search..." /> {suggestions.length > 0 && ( <ul> {suggestions.map((suggestion, index) => ( <li key={index}>{suggestion}</li> ))} </ul> )} </div> ); }; export default SearchAutocomplete;
Finally, include this SearchAutocomplete
component in your main application file, usually App.js
:
// src/App.js import React from 'react'; import './App.css'; import SearchAutocomplete from './SearchAutocomplete'; function App() { return ( <div className="App"> <h1>Search Autocomplete Example</h1> <SearchAutocomplete /> </div> ); } export default App;
With that, you now have a functioning search autocomplete typeahead component in React! You can further enhance this by adding features such as keyboard navigation, highlighting matched characters, or fetching real-time suggestions from an API.
24/08/2024 | ReactJS
14/09/2024 | ReactJS
14/09/2024 | ReactJS
24/08/2024 | ReactJS
24/08/2024 | ReactJS
22/09/2024 | ReactJS
16/07/2024 | ReactJS
14/09/2024 | ReactJS
24/08/2024 | ReactJS