Implementing a Search Dropdown in React Native with react-native-autocomplete-dropdown

Autocomplete dropdowns have become a staple in many popular apps like Google, Uber, DoorDash, and Instagram. These dropdowns significantly…

Autocomplete dropdowns have become a staple in many popular apps like Google, Uber, DoorDash, and Instagram. These dropdowns significantly improve user experience by allowing users to quickly search and navigate to app features. Adding this functionality to the landing screen of your mobile app can enhance usability, especially for non-technical users.

In this article, I’ll show you how to implement a search dropdown using the react-native-autocomplete-dropdown library in a React Native/Expo project.

Why react-native-autocomplete-dropdown?

react-native-autocomplete-dropdown is a powerful library that offers:

  • A dropdown picker with search and autocomplete functionality.
  • Support for custom components and search algorithms.
  • Easy integration into existing projects.

Getting Started

1. Install the Library

Install the package using yarn:

yarn add react-native-autocomplete-dropdown

2. Add the Provider

Wrap your app’s root component with the AutocompleteDropdownContextProvider:

import { AutocompleteDropdownContextProvider } from "react-native-autocomplete-dropdown"; 
 
<AutocompleteDropdownContextProvider> 
  <AppRoot /> 
</AutocompleteDropdownContextProvider>

3. Add a Basic Dropdown

Here’s a simple example of adding the dropdown to your App:

import React, { useState } from "react"; 
import { AutocompleteDropdown } from "react-native-autocomplete-dropdown"; 
 
const Home = () => { 
  const [selectedItem, setSelectedItem] = useState(null); 
 
  return ( 
    <AutocompleteDropdown 
      clearOnFocus={false} 
      closeOnBlur={true} 
      closeOnSubmit={false} 
      initialValue={{ id: '2' }} // Example initial value 
      onSelectItem={setSelectedItem} 
      dataSet={[ 
        { id: '1', title: 'Alpha' }, 
        { id: '2', title: 'Beta' }, 
        { id: '3', title: 'Gamma' }, 
      ]} 
    /> 
  ); 
}; 
 
export default Home;

Advanced Customization

To create a more dynamic and functional search dropdown, follow the steps below.

4. Update Items and Search Algorithm

Here’s an updated example where:

  • Each item has a title and subtitle.
  • The search algorithm works with both fields.
import React, { useCallback, useEffect, useRef, useState } from "react"; 
import { useIsFocused } from "@react-navigation/native"; 
import { 
  AutocompleteDropdown, 
  AutocompleteDropdownRef, 
} from "react-native-autocomplete-dropdown"; 
import AutocompleteText from "./AutocompleteText"; 
 
const defaultSuggestionsList = [ 
  { id: "1", title: "Account Info", subtitle: "Update account information" }, 
  { id: "2", title: "Support", subtitle: "Bug Report, Feature Request, Help Center" }, 
]; 
 
const SearchDropDown = () => { 
  const [suggestionsList, setSuggestionsList] = useState(defaultSuggestionsList); 
  const dropdownController = useRef(null); 
  const isFocused = useIsFocused(); 
 
  useEffect(() => { 
    if (!isFocused) { 
      dropdownController?.current?.close(); 
    } 
  }, [isFocused]); 
 
  const handleSelectItem = (item) => { 
    if (item?.title === "Account Info") { 
      // Handle the selection 
    } 
  }; 
 
  const getSuggestions = useCallback((query) => { 
    if (!query || query.length < 1) { 
      setSuggestionsList(defaultSuggestionsList); 
      return; 
    } 
    const lowerQuery = query.toLowerCase(); 
    const filteredSuggestions = defaultSuggestionsList.filter( 
      (item) => 
        item.title.toLowerCase().includes(lowerQuery) || 
        item.subtitle.toLowerCase().includes(lowerQuery) 
    ); 
    setSuggestionsList(filteredSuggestions); 
  }, []); 
 
  return ( 
    <AutocompleteDropdown 
      controller={(controller) => { 
        dropdownController.current = controller; 
      }} 
      closeOnSubmit 
      onSelectItem={handleSelectItem} 
      dataSet={suggestionsList} 
      onChangeText={getSuggestions} 
      textInputProps={{ 
        placeholder: "Search", 
        style: { fontSize: 18, paddingLeft: 20 }, 
      }} 
      renderItem={(item, searchText) => <AutocompleteText item={item} searchText={searchText} />} 
    /> 
  ); 
}; 
 
export default SearchDropDown;

5. Customize the Autocomplete Text Component

import React, { memo } from "react"; 
import { Text, View } from "react-native"; 
 
const AutocompleteText = ({ 
    item, 
    searchText, 
}: { 
    item: SearchFilterType; 
    searchText: string; 
}) => { 
    const regex = new RegExp(`(${searchText})`, "i"); 
    const arrayTitle = 
        searchText !== "" ? item?.title?.split(regex) : [item?.title]; 
    const arraySubtitle = 
        searchText !== "" ? item?.subtitle?.split(regex) : [item?.subtitle]; 
 
    return ( 
        <View style={{ paddingHorizontal: 15, paddingVertical: 10 }}> 
            <View style={{ flexDirection: "row" }}> 
                {arrayTitle?.map((title, index) => ( 
                    <Text 
                        key={index} 
                        style={{ fontWeight: title?.toLowerCase() === searchText.toLowerCase() ? "700" : "600" }} 
                    > 
                        {title} 
                    </Text> 
                ))} 
            </View> 
 
            <View style={{ flexDirection: "row" }}> 
                {arraySubtitle?.map((subtitle, index) => ( 
                    <Paragraph 
                        key={index} 
                        style={{ fontWeight: title?.toLowerCase() === searchText.toLowerCase() ? "700" : "600" }} 
                    > 
                        {subtitle} 
                    </Paragraph> 
                ))} 
            <View> 
        </View> 
    ); 
}; 
 
export default memo(AutocompleteText);

Key Features Explained

  1. closeOnSubmit: Automatically closes the dropdown when a selection is made.
  2. Search Algorithm: Filters the list using the includes method for both title and subtitle fields.
  3. Regex Highlighting: Highlights matching text in search results dynamically.
  4. dropdownController: Ensures the dropdown closes when navigating away from the screen. (I have noticed that there is a bug sometimes, when navigating to a new screen, that the popup does not go away)

Conclusion

Integrating a search dropdown into your React Native app is straightforward with the react-native-autocomplete-dropdown library. The advanced example here demonstrates how to customize it to meet various requirements, such as handling titles and subtitles or highlighting search terms. This approach not only improves usability but also enhances the overall app experience.

Happy coding! 🚀

Try BanKan Board — The Project Management App Made for Developers, by Developers

If you’re tired of complicated project management tools with story points, sprints, and endless processes, BanKan Board is here to simplify your workflow. Built with developers in mind, BanKan Board lets you manage your projects without the clutter.

Key Features:

  • No complicated processes: Focus on what matters without the overhead of traditional project management systems.
  • Claude AI Assistant: Get smart assistance to streamline your tasks and improve productivity.
  • Free to Use: Start using it without any upfront cost.
  • Premium Features: Upgrade to unlock advanced functionality tailored to your team’s needs.

Whether you’re building a side project, managing a team, or collaborating on open-source software, BanKan Board is designed to make your life easier. Try it today!

Get Started with BanKan Board — It’s Free!