CodingMSTR LogoCodingMSTR
React Search Bar with Suggestion or Auto Complete Source Code

React Search Bar with Suggestion or Auto Complete Source Code

Free

<br>Build a Custom React Search Bar with Suggestions&nbsp;

Category: React
Added On: April 5, 2024
Developer: By Praveen

For any customization or code setup, feel free to contact us. We also offer deployment on live servers.

For any issues related to downloading, email me at devpraveenkr@gmail.com

Need additional support or customization? Contact me!

Project Screenshots

No screenshots available

Project Description


To enhance UI please install Tailwind CSS in your React JS
Source Code for React JS Search Bar with Suggestions and Filters

import React, { useState } from 'react';

const SearchBar = () => {
    const [query, setQuery] = useState('');
    const [suggestions, setSuggestions] = useState([]);


    const handleChange = (event) => {
        const userInput = event.target.value;
        setQuery(userInput);

     
        fetchSuggestions(userInput);
    };

 
    const fetchSuggestions = (input) => {
        if (input) {
         
            const mockSuggestions = [
                'John Smith', 'Alice Johnson', 'Michael Brown', 'Jennifer Davis', 'David Wilson',
                'Mary Martinez', 'James Anderson', 'Patricia Thomas', 'Robert Taylor', 'Linda Lee',
                'William White', 'Elizabeth Harris', 'Christopher Clark',
'Barbara Young', 'Joseph Walker',
                'Margaret Rodriguez', 'David Martinez', 'Anna King',
'Thomas Green', 'Patricia Harris'
            ];

            // Filter suggestions based on user input
            const filteredSuggestions = mockSuggestions.filter(
                (suggestion) =>
                    suggestion.toLowerCase().indexOf(input.toLowerCase()) > -1
            );

            // Update the suggestions state
            setSuggestions(filteredSuggestions);
        } else {
            setSuggestions([]);
        }

    };

    return (
        <div className="flex justify-center items-center mt-64">
            <div className="w-full max-w-lg">
                <h1 className="text-lg">Search Bar With Suggestion</h1>
                <div className="mt-2">
                    <input
                        type="text"
                        value={query}
                        onChange={handleChange}
                        placeholder="Search..."
                        className="w-full px-4 py-2 rounded-lg border border-gray-300
focus:outline-none focus:border-blue-500"
                    />
                    <ul className="bg-slate-200 rounded-md max-h-64 overflow-y-auto">
                        {suggestions.map((suggestion, index) => (
                            <li key={index}
className="px-4 py-2 text-left border-b border-gray-300">
{suggestion}</li>
                        ))}
                    </ul>
                </div>
            </div>

        </div>
    );
};

export default SearchBar;