### Install and Run Example Project Source: https://github.com/onmotion/react-native-autocomplete-dropdown/blob/main/README.md Commands to set up and run the example project for the autocomplete dropdown. This includes installing dependencies and starting the application on iOS or Android. ```bash cd example yarn install yarn pods yarn ios yarn android ``` -------------------------------- ### Install react-native-svg Source: https://github.com/onmotion/react-native-autocomplete-dropdown/blob/main/README.md Ensure react-native-svg is installed by following its installation guide and running the yarn add command. ```bash yarn add react-native-svg ``` -------------------------------- ### Install react-native-autocomplete-dropdown Source: https://github.com/onmotion/react-native-autocomplete-dropdown/blob/main/README.md Install the library using Yarn or npm. For version 3.x, specify the version. ```bash yarn add react-native-autocomplete-dropdown ``` ```bash npm install react-native-autocomplete-dropdown ``` ```bash yarn add react-native-autocomplete-dropdown@3.1.5 ``` -------------------------------- ### iOS Pod Install Source: https://github.com/onmotion/react-native-autocomplete-dropdown/blob/main/README.md Run npx pod-install to install the react-native-svg dependency for iOS if it's not already installed. ```bash npx pod-install ``` -------------------------------- ### Install react-native-autocomplete-dropdown Source: https://context7.com/onmotion/react-native-autocomplete-dropdown/llms.txt Install the package and its peer dependency react-native-svg using yarn. For iOS, ensure CocoaPods are installed. ```bash yarn add react-native-autocomplete-dropdown react-native-svg # iOS — install CocoaPods npx pod-install ``` -------------------------------- ### Local Dataset Example Source: https://github.com/onmotion/react-native-autocomplete-dropdown/blob/main/README.md Example of using AutocompleteDropdown with a local dataset. Configure properties like clearOnFocus, closeOnBlur, closeOnSubmit, initialValue, and onSelectItem. ```javascript const [selectedItem, setSelectedItem] = useState(null); ; ``` -------------------------------- ### Setup AutocompleteDropdownContextProvider Source: https://context7.com/onmotion/react-native-autocomplete-dropdown/llms.txt Wrap your application's root or a Modal with AutocompleteDropdownContextProvider. This context wrapper is required for positioning the floating suggestion list and accepts an optional headerOffset to adjust for fixed navigation headers. ```tsx import React from 'react' import { SafeAreaView, KeyboardAvoidingView, Platform, ScrollView } from 'react-native' import { AutocompleteDropdownContextProvider } from 'react-native-autocomplete-dropdown' import { useHeaderHeight } from '@react-navigation/elements' export default function RootLayout({ children }: { children: React.ReactNode }) { const headerHeight = useHeaderHeight() return ( // headerOffset shifts the dropdown list below the navigation bar {children} ) } ``` -------------------------------- ### Configuring Autocomplete Dropdown with IAutocompleteDropdownProps Source: https://context7.com/onmotion/react-native-autocomplete-dropdown/llms.txt Customize the dropdown's data, behavior, search, appearance, and event handling using the extensive props interface. This example shows a representative configuration covering various categories. ```typescript import type { IAutocompleteDropdownProps } from 'react-native-autocomplete-dropdown' // Representative configuration covering all categories of props: const config: Partial = { // Data dataSet: [{ id: '1', title: 'Example' }], initialValue: { id: '1' }, // or just the string '1' // Behavior clearOnFocus: true, // clear typed text when input is focused closeOnBlur: false, // keep list open after blur closeOnSubmit: false, // keep list open on keyboard submit editable: true, // false → tap-to-open (select mode) useFilter: true, // false → disable built-in client filtering debounce: 300, // ms to debounce onChangeText // Search caseSensitive: false, ignoreAccents: true, // é === e trimSearchText: true, matchFrom: 'any', // 'start' to match prefix only // Appearance inputHeight: 40, suggestionsListMaxHeight: 200, direction: 'down', // 'up' | 'down' | auto-calculated theme: 'light', // 'light' | 'dark' | OS default showChevron: true, showClear: true, enableLoadingIndicator: true, // Loading loading: false, // Events onChangeText: (text) => console.log('typed:', text), onSelectItem: (item) => console.log('selected:', item), onClear: () => console.log('cleared'), onChevronPress: () => console.log('chevron pressed'), onOpenSuggestionsList: (isOpen) => console.log('list open:', isOpen), onBlur: (e) => console.log('blur'), onFocus: (e) => console.log('focus'), onSubmit: (e) => console.log('submit:', e.nativeEvent.text), // Custom render renderItem: (item, searchText) => null, EmptyResultComponent: null, emptyResultText: 'Nothing found', InputComponent: undefined, // replace TextInput with custom component ItemSeparatorComponent: undefined, // Styles containerStyle: {}, inputContainerStyle: {}, rightButtonsContainerStyle: {}, suggestionsListContainerStyle: {}, suggestionsListTextStyle: {}, textInputProps: { placeholder: 'Search…' }, flatListProps: {}, // Custom icons ChevronIconComponent: undefined, ClearIconComponent: undefined, RightIconComponent: undefined, LeftComponent: undefined, onRightIconComponentPress: () => {}, } ``` -------------------------------- ### Context Provider with Header Offset Source: https://github.com/onmotion/react-native-autocomplete-dropdown/blob/main/README.md If you have a header component, pass an offset to the AutocompleteDropdownContextProvider, for example, using useHeaderHeight from react navigation. ```javascript //...import { useHeaderHeight } from '@react-navigation/elements'; //... const headerHeight = useHeaderHeight(); //... ``` -------------------------------- ### Import AutocompleteDropdown Source: https://github.com/onmotion/react-native-autocomplete-dropdown/blob/main/README.md Import the AutocompleteDropdown component from the package. ```javascript import { AutocompleteDropdown } from 'react-native-autocomplete-dropdown'; ``` -------------------------------- ### Wrap Root Component with Context Provider Source: https://github.com/onmotion/react-native-autocomplete-dropdown/blob/main/README.md Wrap your root component with AutocompleteDropdownContextProvider. The dropdown's position is relative to this provider. ```javascript import { AutocompleteDropdownContextProvider } from 'react-native-autocomplete-dropdown'; ``` -------------------------------- ### Apply Dark Theme to AutocompleteDropdown Source: https://context7.com/onmotion/react-native-autocomplete-dropdown/llms.txt Use the `theme` prop set to 'dark' to apply the built-in dark theme. Custom colors can be applied via style props. ```tsx import React, { memo, useState } from 'react' import { AutocompleteDropdown, AutocompleteDropdownItem, } from 'react-native-autocomplete-dropdown' // Built-in dark theme token values: // inputBackgroundColor: '#1c1c1e' // inputTextColor: '#fff' // suggestionsListBackgroundColor: '#151516' // itemSeparatorColor: '#3e3e41' export const DarkDropdown = memo(() => { const [selected, setSelected] = useState(null) return ( ) }) ``` -------------------------------- ### Custom Icons and Action Buttons Source: https://context7.com/onmotion/react-native-autocomplete-dropdown/llms.txt Replace default icons using `RightIconComponent` and `ClearIconComponent`. Use `RightIconComponent` with `onRightIconComponentPress` to implement custom actions, such as toggling the dropdown. ```tsx import React, { memo, useRef, useState } from 'react' import { Text } from 'react-native' import { Smile, Search } from 'react-native-feather' import { AutocompleteDropdown, AutocompleteDropdownItem, IAutocompleteDropdownRef, } from 'react-native-autocomplete-dropdown' export const CustomIconExample = memo(() => { const controllerRef = useRef(null) const [selected, setSelected] = useState(null) return ( { controllerRef.current = ref }} onSelectItem={setSelected} clearOnFocus={false} showChevron={false} // hide default chevron RightIconComponent={} // custom icon button onRightIconComponentPress={() => controllerRef.current?.toggle()} ClearIconComponent={} // custom clear icon /> ) }) ``` -------------------------------- ### Customization Props Source: https://github.com/onmotion/react-native-autocomplete-dropdown/blob/main/README.md Props that allow customization of the component's appearance and behavior. ```APIDOC ## Customization Props ### `renderItem` **Description**: A function that returns JSX for rendering each item in the suggestions list. If it returns `null`, the item will not be displayed. **Signature**: `(item, searchText) => JSX | null` ### `controller` **Description**: Provides a reference to the module controller, offering methods to manage the dropdown's state. **Methods**: `close`, `open`, `toggle`, `clear`, `setInputText`, `setItem` ### `containerStyle` **Description**: Style object for the main container view. **Type**: `ViewStyle` ### `rightButtonsContainerStyle` **Description**: Style object for the container of right-side buttons. **Type**: `ViewStyle` ### `suggestionsListContainerStyle` **Description**: Style object for the container of the suggestions list. **Type**: `ViewStyle` ### `suggestionsListTextStyle` **Description**: Style object for the text of items within the suggestions list. **Type**: `TextStyle` ### `ChevronIconComponent` **Description**: Custom React component to render the chevron icon. **Type**: `React.Component` ### `ClearIconComponent` **Description**: Custom React component to render the clear icon. **Type**: `React.Component` ### `EmptyResultComponent` **Description**: Custom React component to replace the default component displayed when no results are found. **Type**: `React.Component` ### `InputComponent` **Description**: Custom React component to use as the input element. **Type**: `React.ComponentType` ### `emptyResultText` **Description**: Custom text to display when no results are found, replacing the default 'Nothing found'. **Type**: `string` **Default**: "Nothing found" ### `textInputProps` **Description**: Props to be passed directly to the underlying text input element. **Type**: `TextInputProps` ### `flatListProps` **Description**: Props to be passed directly to the underlying `FlatList` component used for displaying suggestions. **Type**: `FlatListProps` ``` -------------------------------- ### Remote Data Fetching with AutocompleteDropdown Source: https://context7.com/onmotion/react-native-autocomplete-dropdown/llms.txt Use this snippet for server-side search. Set `useFilter={false}` to disable client-side filtering, pass `loading` state for a spinner, and `debounce` to throttle API calls. Set `dataSet` to `null` to clear suggestions. ```tsx import React, { memo, useCallback, useState } from 'react' import { Text } from 'react-native' import { AutocompleteDropdown, AutocompleteDropdownItem, } from 'react-native-autocomplete-dropdown' export const PostSearch = memo(() => { const [loading, setLoading] = useState(false) const [suggestions, setSuggestions] = useState(null) const [selectedItem, setSelectedItem] = useState(null) const fetchSuggestions = useCallback(async (query: string) => { if (query.length < 3) { setSuggestions(null) return } setLoading(true) try { const res = await fetch('https://jsonplaceholder.typicode.com/posts') const data: Array<{ id: number; title: string }> = await res.json() const filtered = data .filter(p => p.title.toLowerCase().includes(query.toLowerCase())) .map(p => ({ id: String(p.id), title: p.title })) setSuggestions(filtered) } catch (err) { console.error('Fetch failed:', err) setSuggestions(null) } finally { setLoading(false) } }, []) return ( <> setSuggestions(null)} EmptyResultComponent={No results found} textInputProps={{ placeholder: 'Search posts (type 3+ chars)…', autoCorrect: false, autoCapitalize: 'none', }} suggestionsListMaxHeight={300} /> Selected id: {selectedItem?.id ?? 'none'} ) }) ``` -------------------------------- ### Event Handlers Source: https://github.com/onmotion/react-native-autocomplete-dropdown/blob/main/README.md These are event handlers that can be passed as props to the component to respond to user interactions. ```APIDOC ## Event Handlers ### `onSelectItem` **Description**: Event triggered when an item is selected from the suggestions list. ### `onOpenSuggestionsList` **Description**: Event triggered when the suggestions list is opened. ### `onChevronPress` **Description**: Event triggered when the chevron icon is pressed. ### `onClear` **Description**: Event triggered when the clear button is pressed. ### `onSubmit` **Description**: Event triggered when the submit button on the keyboard is pressed. ### `onBlur` **Description**: Event fired when the text input loses focus. ### `onFocus` **Description**: Event fired when the text input gains focus. ``` -------------------------------- ### Custom Item Rendering with Highlight Source: https://context7.com/onmotion/react-native-autocomplete-dropdown/llms.txt Use the `renderItem` prop to customize how each item is displayed. You can conditionally hide items by returning `null`. The `searchText` parameter can be used to highlight matching parts of the item's title. ```tsx import React, { memo, useState } from 'react' import { Text, View } from 'react-native' import { AutocompleteDropdown, AutocompleteDropdownItem, } from 'react-native-autocomplete-dropdown' const fruits: AutocompleteDropdownItem[] = [ { id: '1', title: '🍎 Apple' }, { id: '2', title: '🍌 Banana' }, { id: '3', title: '🍇 Grape' }, { id: '4', title: '🍊 Orange' }, ] export const CustomRenderExample = memo(() => { const [selected, setSelected] = useState(null) return ( { // Returning null hides the item from the list if (item.title?.toLowerCase().includes('banana')) return null return ( {item.title?.split(' ')[0]} {item.title?.split(' ').slice(1).join(' ')} {searchText ? ( matches "{searchText}" ) : null} ) }} /> ) }) ``` -------------------------------- ### Autocomplete Dropdown with Remote Data Source: https://github.com/onmotion/react-native-autocomplete-dropdown/blob/main/README.md Demonstrates fetching data from a remote API and filtering it for autocomplete suggestions. Requires at least 3 characters to be typed before fetching. The `useFilter={false}` prop prevents duplicate renders. ```javascript import React, { memo, useCallback, useRef, useState } from 'react' import { Button, Dimensions, Text, View, Platform } from 'react-native' import { AutocompleteDropdown } from 'react-native-autocomplete-dropdown' export const RemoteDataSetExample2 = memo(() => { const [loading, setLoading] = useState(false) const [suggestionsList, setSuggestionsList] = useState(null) const [selectedItem, setSelectedItem] = useState(null) const dropdownController = useRef(null) const searchRef = useRef(null) const getSuggestions = useCallback(async q => { const filterToken = q.toLowerCase() console.log('getSuggestions', q) if (typeof q !== 'string' || q.length < 3) { setSuggestionsList(null) return } setLoading(true) const response = await fetch('https://jsonplaceholder.typicode.com/posts') const items = await response.json() const suggestions = items .filter(item => item.title.toLowerCase().includes(filterToken)) .map(item => ({ id: item.id, title: item.title, })) setSuggestionsList(suggestions) setLoading(false) }, []) const onClearPress = useCallback(() => { setSuggestionsList(null) }, []) const onOpenSuggestionsList = useCallback(isOpened => {}, []) return ( <> { dropdownController.current = controller }} // initialValue={'1'} direction={Platform.select({ ios: 'down' })} dataSet={suggestionsList} onChangeText={getSuggestions} onSelectItem={item => { item && setSelectedItem(item.id) }} debounce={600} suggestionsListMaxHeight={Dimensions.get('window').height * 0.4} onClear={onClearPress} // onSubmit={(e) => onSubmitSearch(e.nativeEvent.text)} onOpenSuggestionsList={onOpenSuggestionsList} loading={loading} useFilter={false} // set false to prevent rerender twice textInputProps={{ placeholder: 'Type 3+ letters (dolo...)' , autoCorrect: false, autoCapitalize: 'none', style: { borderRadius: 25, backgroundColor: '#383b42', color: '#fff', paddingLeft: 18, }, }} rightButtonsContainerStyle={{ right: 8, height: 30, alignSelf: 'center', }} inputContainerStyle={{ backgroundColor: '#383b42', borderRadius: 25, }} suggestionsListContainerStyle={{ backgroundColor: '#383b42', }} containerStyle={{ flexGrow: 1, flexShrink: 1 }} renderItem={(item, text) => {item.title}} // ChevronIconComponent={} // ClearIconComponent={} inputHeight={50} showChevron={false} closeOnBlur={false} // showClear={false} />