logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Creating a Search Autocomplete Typeahead Component in React

author
Generated by
Abhishek Goyan

14/09/2024

React

Sign in to read full article

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.

Getting Started

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.

Step 1: Setting Up the Component Skeleton

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;

Step 2: Adding State Management

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;

Step 3: Filtering Suggestions

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> ); };

Step 4: Displaying Suggestions

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> );

Step 5: Styling the Component

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; }

Step 6: Putting It All Together

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;

Step 7: Using the Component

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.

Popular Tags

ReactJavaScriptWeb Development

Share now!

Like & Bookmark!

Related Collections

  • React Interview Challenges: Essential Coding Problems

    14/09/2024 | ReactJS

  • Mastering React Concepts

    24/08/2024 | ReactJS

Related Articles

  • Forms in React: Handling User Input

    24/08/2024 | ReactJS

  • Mastering React JS Performance Optimization

    22/09/2024 | ReactJS

  • Handling Authentication in React: A Comprehensive Guide

    24/08/2024 | ReactJS

  • Exploring useLayoutEffect vs useEffect in React

    21/07/2024 | ReactJS

  • Testing React Components with Jest and React Testing Library

    24/08/2024 | ReactJS

  • Deploying Your React Application in Docker and Cloud Run

    24/08/2024 | ReactJS

  • Implementing a Dynamic Theme Switcher (Light/Dark Mode) in Your Web Application

    14/09/2024 | ReactJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design