HomeOur TeamContact

Remote List Customization Auto Complete

By Utkarsh Lubal
Published in Others
May 06, 2023
1 min read
Remote List Customization Auto Complete

Table Of Contents

01
Introduction
02
Installation
03
Example
04
Tutorial

Introduction

React Native Autocomplete is a library that allows users to easily create an autocomplete input field in their React Native app. Autocomplete is a feature that can be useful for many types of applications, especially those that rely heavily on user input, such as search engines or e-commerce apps.

With the React Native Autocomplete library, developers can create an input field that will display a list of suggested values based on the user’s input. This can be done by simply passing an array of options to the Autocomplete component. The user’s input is then matched against the options, and a list of matches is displayed.

The Autocomplete component also allows for customization of the suggestion list, including custom rendering of individual options and the ability to limit the number of options displayed at once. Overall, React Native Autocomplete is a powerful and flexible library that can help developers create more user-friendly and efficient input fields in their React Native apps.

Events

eventInfo
onTypingText is entered. The callback can be delayed with option autoCompleteFetchRequestDelay.
onSelectA cell in the suggestions list is selected.
onFocusText input get focus.
onBlurText input lost focus.

Other events from Text Input are avalaible.

Global options

optiontypeInfo
cellComponentstringName of a React Native component used to render cells. If null, use the default rendering.
suggestionsarrayIf using default cell rendering specify an Array of string, otherwise any object.
autoCompleteFetchRequestDelaynumberDelay in milliseconds before retrieving suggestions.
maximumNumberOfAutoCompleteRowsnumberNumber of suggestions displayed.
showTextFieldDropShadowWhenAutoCompleteTableIsOpenboolDisplay a drop shadow around the text field.
autoCompleteTableViewHiddenboolIf true, the suggestions list will be hidden.
autoCompleteTableBorderColorcolorSet suggestions list border color.
autoCompleteTableBorderWidthnumberSet suggestions list border color.
autoCompleteTableBackgroundColorcolorSet suggestions list border size.
autoCompleteTableCornerRadiusnumberSet suggestions list background color.
autoCompleteTableTopOffsetnumberSet the distance between the text field and the suggestions list.
autoCompleteTableLeftOffsetnumberSet the left offset between the container and the suggestions list.
autoCompleteTableSizeOffsetnumberSet the offset of the suggestions list size. Combined with autoCompleteTableLeftOffset, you can reduce the width of the suggestions list and to center it. Exemple: autoCompleteTableLeftOffset=20 autoCompleteTableSizeOffset=40
autoCompleteRowHeightnumberHeight of cells in the suggestions list.

Default cell rendering options

optiontypeInfo
autoCompleteFontSizenumberFont Size used to display text.
autoCompleteRegularFontNamestringFont used to display text.
autoCompleteBoldFontNamestringFont used to display suggestion text.
autoCompleteTableCellTextColorcolorText Color used to display text.
autoCompleteTableCellBackgroundColorcolorBackground color of cells.
applyBoldEffectToAutoCompleteSuggestionsboolIf false, disable bold effect on suggestion text.
reverseAutoCompleteSuggestionsBoldEffectboolReverse the bold effect.

Installation

npm install react-native-autocomplete

And

npm install react-native-vector-icons –save

Example

import React, { memo, useCallback, useRef, useState } from 'react'
import { Button, Dimensions, Text, View, Platform, SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  useColorScheme,
  KeyboardAvoidingView, } from 'react-native'
import { AutocompleteDropdown } from 'react-native-autocomplete-dropdown'

import Feather from 'react-native-vector-icons/Feather'
Feather.loadFont()

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 (
    <>
    <SafeAreaView style={{ flex: 1 }}>
      <StatusBar barStyle={'light-content'} />
      <KeyboardAvoidingView
        style={{ flex: 1 }}
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        enabled>
        <ScrollView
          nestedScrollEnabled
          keyboardDismissMode="on-drag"
          keyboardShouldPersistTaps="handled"
          contentInsetAdjustmentBehavior="automatic"
          contentContainerStyle={{ paddingBottom: 200 }}
          style={styles.scrollContainer}>
          <View style={[styles.container]}>
                        <Text style={styles.sectionTitle}>Remote list customization</Text>
        <AutocompleteDropdown
          ref={searchRef}
          controller={controller => {
            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) => <Text style={{ color: '#fff', padding: 15 }}>{item.title}</Text>}
          ChevronIconComponent={<Feather name="chevron-down" size={20} color="#fff" />}
          ClearIconComponent={<Feather name="x-circle" size={18} color="#fff" />}
          inputHeight={50}
          showChevron={false}
          closeOnBlur={false}
          //  showClear={false}
        />
        <View style={{ width: 10 }} />
        <Button style={{ flexGrow: 0 }} title="Toggle" onPress={() => dropdownController.current.toggle()} />
      </View>
      <Text style={{ color: '#668', fontSize: 13 }}>Selected item id: {JSON.stringify(selectedItem)}</Text>

        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
    </>
  )
})
const styles = StyleSheet.create({
  scrollContainer: {
    flex: 1,
  },
  container: {
    padding: 20,
  },
  title: {
    textAlign: 'center',
    fontSize: 25,
    marginBottom: 50,
  },
  section: {
    marginBottom: 40,
  },
  sectionTitle: {
    fontWeight: 'bold',
    marginBottom: 3,
  },
})

export default RemoteDataSetExample2;

Tutorial

Coming Soon…


Previous Article
Rotation Gesture recognizers
Utkarsh Lubal

Utkarsh Lubal

Full Stack Developer

Related Posts

Exploring Alternative Emulators for React Native Development
Exploring Alternative Emulators for React Native Development
January 20, 2024
1 min

Quick Links

Advertise with usAbout UsContact Us

Social Media