
Build 10x products in minutes by chatting with AI - beyond just a prototype.
When developing a modern web application, enhancing the user experience is paramount. One way to achieve this is by implementing a react search bar with suggestions. This feature not only improves the usability of your app but also guides users through their searches, making the process faster and more intuitive. If you're wondering how to create such a dynamic and responsive search box in ReactJS, you've come to the right place.
Before diving into the code, let's establish what an autocomplete component is. Essentially, it's an input field that provides real-time suggestions to the user as they type. These suggestions are typically based on an array of data that can be filtered according to the string searched. React search autocomplete components are highly customizable, allowing you to tailor the look and functionality to your app's needs.
To begin, you'll need to set up a new React project. Once you have your project directory, navigate to it in your terminal and run the following command to create a new React app:
1npx create-react-app autocomplete-search-app
This command scaffolds a new React project with all the necessary files and folder structure you'll need. Navigate to your project directory, and you're ready for the next step.
Now that we have our React app, let's discuss the folder structure. A tidy folder structure ensures that our components and utilities are organized and easily accessible. Create folders for components, styles, and utils in your project's src directory**.** This will help us manage our autocomplete component, CSS files, and helper functions.
With our folder structure in place, it's time to add the react-search-autocomplete package to our project. Run the following command in your project directory:
1npm install react-search-autocomplete
This command fetches the latest version of the react-search-autocomplete package and adds it to our project's dependencies. Now we're all set to import and use it in our app.
Before we dive into the autocomplete component, let's prepare our main app component. Open the App.js file in your editor. Here, we'll import React and set up the basic structure of our app. The app header will be the first component users see, so let's make it welcoming.
1 2 3 4 5 6 7 8 9 10 11 12 13 14import React from 'react'; import './App.css'; // Import your main CSS file to style the app function App() { return ( <div className="App"> <header className="App-header"> {/* We'll add our search component here soon */} </header> </div> ); } export default App; // Don't forget to export your app component!
In the code above, we've prepared a functional component for our app and included a placeholder for where our search component will eventually live. The export default App statement makes our App component available for use in other parts of our project.
The heart of our search functionality lies in the input field, where users will type their queries. Let's create this essential part of our app. In the components folder, make a new file called SearchBar.js. This file will house our autocomplete component.
1 2 3 4 5 6 7 8 9 10 11 12 13 14import React from 'react'; import { ReactSearchAutocomplete } from 'react-search-autocomplete'; function SearchBar() { // We'll add the logic for handling searches here soon return ( <div style={{ width: '100%' }}> {/* Our autocomplete component will go here */} </div> ); } export default SearchBar;
We've set up a functional component to render our search bar in the snippet above. Notice how we've prepared a space to include our autocomplete component, which we'll get to shortly.
Now, let's integrate the autocomplete component into our SearchBar component. The autocomplete component will display suggestions to the user as they type, making the search experience intuitive and efficient.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38import React from 'react'; import { ReactSearchAutocomplete } from 'react-search-autocomplete'; function SearchBar() { const items = [ { id: 0, name: 'HTML' }, { id: 1, name: 'JavaScript' }, { id: 2, name: 'Basic' }, { id: 3, name: 'PHP' }, { id: 4, name: 'Java' } ]; return ( <div style={{ width: '100%' }}> <ReactSearchAutocomplete items={items} // Additional props and event handlers will be added here /> </div> ); } export default SearchBar;
We've imported the ReactSearchAutocomplete component in the code above and included it in our SearchBar component's render method. The items array will eventually contain the suggestions we want to display to the user.
A well-designed search box is crucial for user engagement. Let's add some CSS to make our search input field stand out. Create a SearchBar.css file in the styles folder and import it into your SearchBar.js file.
1 2 3 4 5/* SearchBar.css */ .search-bar-container { max-width: 500px; margin: auto; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24import React from 'react'; import { ReactSearchAutocomplete } from 'react-search-autocomplete'; import './SearchBar.css'; // Importing our CSS file function SearchBar() { const items = [ { id: 0, name: 'HTML' }, { id: 1, name: 'JavaScript' }, { id: 2, name: 'Basic' }, { id: 3, name: 'PHP' }, { id: 4, name: 'Java' } ]; return ( <div className="search-bar-container"> <ReactSearchAutocomplete items={items} // ...previous props /> </div> ); } export default SearchBar;
With the CSS imported, our search bar will now have a maximum width and be centered on the page, thanks to the styles we defined.
We want to provide immediate and relevant feedback when users interact with the search bar. This is where event handlers come into play. We'll add functions to handle search input, item selection, and hovering.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42import React, { useState } from 'react'; import { ReactSearchAutocomplete } from 'react-search-autocomplete'; import './SearchBar.css'; function SearchBar({ onSearchSelected }) { const [items, setItems] = useState([ { id: 0, name: 'HTML' }, { id: 1, name: 'JavaScript' }, { id: 2, name: 'Basic' }, { id: 3, name: 'PHP' }, { id: 4, name: 'Java' } ]); const handleOnSearch = (string, results) => { // Triggered when the user types in the search input console.log(string, results); }; const handleOnHover = (item) => { // Triggered when the user hovers over an item in the suggestions list console.log('Item hovered:', item); }; const handleOnSelect = (item) => { // Triggered when the user selects an item from the suggestions list console.log('Item selected:', item); onSearchSelected(item); }; return ( <div className="search-bar-container"> <ReactSearchAutocomplete items={items} onSearch={handleOnSearch} onHover={handleOnHover} onSelect={handleOnSelect} /> </div> ); } export default SearchBar;
In the updated code, we've added three functions: handleOnSearch, handleOnHover, and handleOnSelect. These functions will be called when the user searches for a string, hovers over a suggestion, and selects a suggestion.
Our autocomplete component needs to communicate with a backend service to provide real-time suggestions. This could be an internal API or a third-party service, like Google Maps API, depending on the use case. Let's set up the basic structure for API requests within our SearchBar component.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63import React, { useState, useEffect } from 'react'; import { ReactSearchAutocomplete } from 'react-search-autocomplete'; function SearchBar() { const [searchTerm, setSearchTerm] = useState(''); const [suggestions, setSuggestions] = useState([]); useEffect(() => { if (searchTerm.trim() === '') { setSuggestions([]); } else { fetchSuggestions(searchTerm); } }, [searchTerm]); const fetchSuggestions = async (searchTerm) => { try { // Replace 'YOUR_API_ENDPOINT' with the actual endpoint of your API const response = await fetch(`YOUR_API_ENDPOINT?query=${encodeURIComponent(searchTerm)}`); const data = await response.json(); setSuggestions(data); // Assuming the API returns an array of suggestions } catch (error) { console.error('Error fetching suggestions:', error); } }; const handleOnSearch = (string) => { setSearchTerm(string); }; const handleOnSelect = (item) => { console.log('Selected:', item); }; const handleOnHover = (item) => { console.log('Hovered:', item); }; const handleOnFocus = () => { console.log('The search input is focused'); }; const handleOnClear = () => { console.log('The search input is cleared'); setSuggestions([]); }; return ( <div style={{ width: 300 }}> <ReactSearchAutocomplete items={suggestions} onSearch={handleOnSearch} onSelect={handleOnSelect} onHover={handleOnHover} onFocus={handleOnFocus} onClear={handleOnClear} placeholder="Type to search" /> </div> ); } export default SearchBar;
In the code snippet above, we've added a useState hook to manage our suggestions state and a fetchSuggestions function that simulates an API call to fetch suggestions based on the user's input.
Once we have our suggestions from the API, we need to update our autocomplete component to display these suggestions. We'll modify the handleOnSearch function to call fetchSuggestions whenever the user types in the search input.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33import React, { useState } from 'react'; import { ReactSearchAutocomplete } from 'react-search-autocomplete'; import './SearchBar.css'; function SearchBar({ onSearchSelected }) { const [suggestions, setSuggestions] = useState([]); const fetchSuggestions = async (searchTerm) => { try { // Replace with your API call logic const response = await fetch(`YOUR_API_ENDPOINT?query=${searchTerm}`); const data = await response.json(); setSuggestions(data); // Update our suggestions state with the API response } catch (error) { console.error('Error fetching suggestions:', error); } }; const handleOnSearch = (string, results) => { // Trigger the API call to fetch suggestions fetchSuggestions(string); }; return ( <div className="search-bar-container"> <ReactSearchAutocomplete items={suggestions} /> </div> ); } export default SearchBar;
By calling fetchSuggestions inside handleOnSearch, we ensure that our autocomplete suggestions are always up to date with the latest data from our backend service.
To further refine the user experience, we can debounce the search input to reduce the number of API calls made while the user is typing. This improves performance and reduces unnecessary load on the server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15import { debounce } from 'lodash'; function SearchBar() { const [suggestions, setSuggestions] = useState([]); // Debounce the fetchSuggestions function const debouncedFetchSuggestions = debounce(fetchSuggestions, 300); const handleOnSearch = (string, results) => { // Use the debounced version of our API call function debouncedFetchSuggestions(string); }; // ...other event handlers and return statement }
In the updated handleOnSearch function, we've introduced a debounced version of fetchSuggestions using the debounce function from Lodash, which will wait for 300 milliseconds after the last keystroke before making the API call.
To make our search bar stand out, we need to customize the autocomplete component to suit our users' needs better. This involves tweaking the behavior and appearance of the suggestions displayed. For instance, we might want to show more information about each suggestion or change how they're rendered based on user interactions.
Let's add a custom rendering function to format our results. This function will allow us to display additional details about each suggestion, such as an id or other relevant information.
1 2 3 4 5 6 7 8 9 10 11 12 13 14function SearchBar() { // ...previous code and state const formatResult = (item) => { return ( <> <span style={{ display: 'block', textAlign: 'left' }}>ID: {item.id}</span> <span style={{ display: 'block', textAlign: 'left' }}>Name: {item.name}</span> </> ); }; // ...other event handlers and return statement }
In the formatResult function above, we're customizing how each result is displayed by including the item's id and name. This function can be passed as a prop to our ReactSearchAutocomplete component.
Visual feedback is key when a user interacts with the search bar. Let's implement visual cues for when a user hovers over an item and selects an item. These interactions can be logged to the console or used to trigger other actions within the app.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15function SearchBar() { // ...previous code and state const handleOnHover = (item) => { // Log the item hovered to the console console.log('Item hovered:', item); }; const handleOnSelect = (item) => { // Log the item selected to the console console.log('Item selected:', item); }; // ...other event handlers and return statement }
The handleOnHover and handleOnSelect functions provide immediate feedback to the user. They can further enhance the search experience, such as displaying additional details about the hovered or selected item.
Accessibility and responsive design ensure that our search bar is usable by everyone, regardless of their device or abilities. We can customize the styles of our autocomplete component to ensure it is both accessible and responsive.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19function SearchBar() { // ...previous code and state const styling = { // Customize the styles of the autocomplete component height: '40px', border: '1px solid #dfe1e5', borderRadius: '4px', backgroundColor: 'white', boxShadow: 'none', hoverBackgroundColor: '#f2f2f2', color: '#212121', fontSize: '14px', fontFamily: 'Helvetica, sans-serif', // Additional styling can be added here }; // ...other event handlers and return statement }
By providing a styling object, we can define the look and feel of our search bar, ensuring it adapts well to different screen sizes and is easy to navigate for users with accessibility needs.
As we conclude our journey of implementing a React search bar with autocomplete suggestions, we've seen how combining modern React practices and the react-search-autocomplete package can create a powerful and user-friendly search experience. From setting up our project and crafting a responsive input field to connecting with backend services and fine-tuning the user interactions, each step has brought us closer to a feature-rich search component.
Remember, the code snippets provided throughout this blog are just the beginning. You can customize and extend the functionality to match the specific needs of your users and your application. The possibilities are endless, Whether by enhancing the visual design, integrating with different APIs, or adding more complex filtering logic.
With your search bar now in place, you're now equipped to build an intuitive search feature that serves your users' needs and elevates your app's overall user experience.