logo

Education

How to Implement a React Search Bar with Dropdown

Authore Name
Daxesh Patel

Software Development Executive - I

Last updated on Jul 11, 2024

When creating a feature-rich web application, a search bar is often a fundamental component that enhances user experience. In the world of React applications, integrating a search bar with a dropdown menu can provide users with a seamless and intuitive interface for finding the data they need.

In this blog, we'll dive into the technical aspects of implementing a React search bar with dropdown, leveraging the powerful react-select library to enrich our React app with a multi-select feature and robust search functionality.

Understanding React Select and Its Importance

react-select is a flexible and customizable select input control for React applications. It provides a robust set of features including single and multi-select capabilities, asynchronous loading, and even creating new options on the fly with a creatable component. The importance of react-select lies in its ability to handle various use cases, from a simple dropdown menu to a complex multi-select feature with search capabilities.

Setting Up the React Application

Before adding a React search bar with dropdown to our app, we need to set up a basic React application. If you haven't already, you can create a new React app using the following command:

1npx create-react-app my-search-dropdown-app 2

Once the app is created, navigate to the project directory:

1cd my-search-dropdown-app 2

Installing React Select

To import react-select into our project, we must install it using npm or yarn. Run the following command to add it to your project:

1npm install react-select 2

or if you prefer yarn:

1yarn add react-select 2

Importing React Select Components

With the library installed, we can now import react-select components into our React component file. For a basic dropdown, we'll need the Select component. If we want to implement a multi-select feature, we'll also import AsyncSelect and makeAnimated for asynchronous data loading and animations respectively.

1import React from 'react'; 2import Select from 'react-select'; 3import AsyncSelect from 'react-select/async'; 4import makeAnimated from 'react-select/animated'; 5

Structuring the Options Array

The options array is a critical part of react-select, as it defines the items displayed in the dropdown menu. Each item in the array is an object with label and value properties. The label is what the user sees, while the value is used behind the scenes.

1const optionsArray = [ 2 { value: 'chocolate', label: 'Chocolate' }, 3 { value: 'strawberry', label: 'Strawberry' }, 4 { value: 'vanilla', label: 'Vanilla' } 5]; 6

Creating the Search Bar Component

Let's create a functional component for our search bar with dropdown. We'll start by setting up the basic structure of the component and importing the necessary React import statements.

1import React, { useState } from 'react'; 2import Select from 'react-select'; 3 4const SearchDropdown = () => { 5 const [selectedOption, setSelectedOption] = useState(null); 6 7 return ( 8 <div> 9 <Select 10 value={selectedOption} 11 onChange={setSelectedOption} 12 options={optionsArray} 13 /> 14 </div> 15 ); 16}; 17 18export default SearchDropdown; 19

Handling the OnChange Event

When a user selects an option from the dropdown, we must handle the onchange event. The onChange prop takes a function to be called with the newly selected option object.

1const handleChange = (option) => { 2 setSelectedOption(option); 3 console.log(`Option selected:`, option); 4}; 5

Then, we update the Select component's onChange prop to use this function:

1<Select 2 value={selectedOption} 3 onChange={handleChange} 4 options={optionsArray} 5/> 6

Adding Multi-Select Functionality

To enable the multi-select feature, we simply need to set the isMulti prop to true. This allows users to select multiple options from the dropdown.

1<Select 2 isMulti 3 value={selectedOption} 4 onChange={handleChange} 5 options={optionsArray} 6/> 7

Styling the Dropdown

You can apply CSS styles to ensure the dropdown aligns with the rest of your React app's design. Create a CSS file and import it into your component file. Then, assign a className to the Select component and define your styles accordingly.

1/* SearchDropdown.css */ 2.search-dropdown { 3 min-width: 300px; 4} 5
1import './SearchDropdown.css'; 2 3// ... 4 5<Select 6 className="search-dropdown" 7 isMulti 8 value={selectedOption} 9 onChange={handleChange} 10 options={optionsArray} 11/> 12

By linking the CSS file with the import statement and using the className prop, you can control the look and feel of the dropdown to match your app's theme.

Implementing Asynchronous Data Loading

For a more dynamic react-select experience, especially when dealing with large datasets or data that needs to be fetched from an API, we can use the AsyncSelect component. This component allows us to load options asynchronously using a promise.

First, we define a function that will load our options. This function, const loadOptions, will typically make an API request and return a promise that resolves to our options array.

1const loadOptions = (inputValue) => { 2 return fetch(`https://api.example.com/search?q=${inputValue}`) 3 .then(response => response.json()) 4 .then(data => data.map(user => ({ label: user.name, value: user.id }))); 5}; 6

Then, we use the AsyncSelect component and pass loadOptions to the loadOptions prop:

1<AsyncSelect 2 cacheOptions 3 loadOptions={loadOptions} 4 defaultOptions 5 onInputChange={handleInputChange} 6/> 7

The cacheOptions prop can be used to cache the loaded options, while defaultOptions can preload the default set of options.

Enhancing the Search Functionality

To refine the search functionality, we can debounce the input to reduce the number of requests made to the server. This means that the search query will only be sent after the user has stopped typing for a specified time.

1import debounce from 'lodash.debounce'; 2 3// ... 4 5const debouncedLoadOptions = debounce(loadOptions, 500); 6 7<AsyncSelect 8 cacheOptions 9 loadOptions={debouncedLoadOptions} 10 defaultOptions 11 onInputChange={handleInputChange} 12/> 13

Managing State with Controlled Components

In React, controlled components are those where React controls the component's state. For our select menu, this means that the state of our component manages the value prop, and any changes to that value are handled by the component's onChange event.

1const [inputValue, setInputValue] = useState(''); 2 3const handleInputChange = (newValue) => { 4 const inputValue = newValue.replace(/\W/g, ''); 5 setInputValue(inputValue); 6 return inputValue; 7}; 8 9// ... 10 11<AsyncSelect 12 value={selectedOption} 13 onChange={handleChange} 14 inputValue={inputValue} 15 onInputChange={handleInputChange} 16 loadOptions={debouncedLoadOptions} 17/> 18 19

Adding Custom Option Components

react-select allows us to customize how options are displayed using the components prop. We can create a custom component to display each option and pass it to the Select component.

1const Option = (props) => { 2 return ( 3 <components.Option {...props}> 4 <span>{props.data.label}</span> 5 {/* Additional custom rendering */} 6 </components.Option> 7 ); 8}; 9 10// ... 11 12<Select 13 components={{ Option }} 14 // ... other props 15/> 16

Conclusion

In this blog, we've explored how to create a react search bar with dropdown using the react-select library. We've covered the basics of setting up the React app, importing the necessary components, and configuring the select menu to meet various requirements such as multi-select and asynchronous data loading.

With react-select, you have the tools to create a powerful search component that can handle a wide array of use cases.

Whether you're building a simple dropdown or a complex search interface with a multi-select feature, react-select offers a solution that is both user-friendly and developer-friendly. By following the examples and code snippets provided, you should now have a solid foundation to implement your own React search bar with the dropdown in your React application.

Short on time? Speed things up with DhiWise!!

Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!

You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.

Sign up to DhiWise for free

Read More