Example of React Native AutoComplete Input

React Native AutoComplete

This is an example of React Native AutoComplete Input. To make an AutoComplete Input we will use Autocomplete component provided by react-native-autocomplete-input.

If you want to show some suggestions to the user while entering the value in an Input you can use AutoComplete Input, to show the hint you have to provide the data as a list or an array to the Autocomplete Input.

Autocomplete Input

<Autocomplete
    autoCapitalize="none"
    autoCorrect={false}
    containerStyle={styles.autocompleteContainer}
    //data to show in suggestion
    data={filteredFilms}
    //default value if you want to set something in input
    defaultValue={
    JSON.stringify(selectedValue) === '{}' ?
    '' :
    selectedValue.title
    }
    // onchange of the text changing the state of the query
    // which will trigger the findFilm method
    // to show the suggestions
    onChangeText={(text) => findFilm(text)}
    placeholder="Enter the film title"
    renderItem={({item}) => (
    //you can change the view you want to show in suggestions
    <TouchableOpacity
        onPress={() => {
        setSelectedValue(item);
        setFilteredFilms([]);
        }}>
        <Text style={styles.itemText}>
            {item.title}
        </Text>
    </TouchableOpacity>
    )}
/>

In this example, we will make an Autocomplete Input which will show the suggestions of the movie’s name if we start typing something. So Let’s get started.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependency

To use Autocomplete component you need to install react-native-autocomplete-input package. To install this

Open the terminal and jump into your project using

cd ProjectName

Run the following command

npm install react-native-autocomplete-input --save

This command will copy all the dependencies into your node_module directory. –save is optional, it is just to update the react-native-autocomplete-input dependency in your package.json file.

Code for AutoComplete Input/ AutoSuggestion Input

Now Open App.js in any code editor and replace the code with the following code

App.js

//Example of React Native AutoComplete Input
//https://aboutreact.com/example-of-react-native-autocomplete-input/

//import React in our code
import React, {useState, useEffect} from 'react';

//import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

//import Autocomplete component
import Autocomplete from 'react-native-autocomplete-input';

const App = () => {
  const [films, setFilms] = useState([]);  // For the main data
  const [filteredFilms, setFilteredFilms] = useState([]); // Filtered data
  const [selectedValue, setSelectedValue] = useState({}); // selected data

  useEffect(() => {
    fetch('https://aboutreact.herokuapp.com/getpost.php?offset=1')
      .then((res) => res.json())
      .then((json) => {
        const {results: films} = json;
        setFilms(films);
        //setting the data in the films state
      })
      .catch((e) => {
        alert(e);
      });
  }, []);

  const findFilm = (query) => {
    //method called everytime when we change the value of the input
    if (query) {
      //making a case insensitive regular expression
      const regex = new RegExp(`${query.trim()}`, 'i');
      //setting the filtered film array according the query
      setFilteredFilms(
          films.filter((film) => film.title.search(regex) >= 0)
      );
    } else {
      //if the query is null then return blank
      setFilteredFilms([]);
    }
  };

  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={styles.container}>
        <Autocomplete
          autoCapitalize="none"
          autoCorrect={false}
          containerStyle={styles.autocompleteContainer}
          //data to show in suggestion
          data={filteredFilms}
          //default value if you want to set something in input
          defaultValue={
            JSON.stringify(selectedValue) === '{}' ?
            '' :
            selectedValue.title
          }
          // onchange of the text changing the state of the query
          // which will trigger the findFilm method
          // to show the suggestions
          onChangeText={(text) => findFilm(text)}
          placeholder="Enter the film title"
          renderItem={({item}) => (
            //you can change the view you want to show in suggestions
            <TouchableOpacity
              onPress={() => {
                setSelectedValue(item);
                setFilteredFilms([]);
              }}>
              <Text style={styles.itemText}>
                  {item.title}
              </Text>
            </TouchableOpacity>
          )}
        />
        <View style={styles.descriptionContainer}>
          {films.length > 0 ? (
            <>
              <Text style={styles.infoText}>
                   Selected Data
              </Text>
              <Text style={styles.infoText}>
                {JSON.stringify(selectedValue)}
              </Text>
            </>
          ) : (
            <Text style={styles.infoText}>
                Enter The Film Title
            </Text>
          )}
        </View>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#F5FCFF',
    flex: 1,
    padding: 16,
    marginTop: 40,
  },
  autocompleteContainer: {
    backgroundColor: '#ffffff',
    borderWidth: 0,
  },
  descriptionContainer: {
    flex: 1,
    justifyContent: 'center',
  },
  itemText: {
    fontSize: 15,
    paddingTop: 5,
    paddingBottom: 5,
    margin: 2,
  },
  infoText: {
    textAlign: 'center',
    fontSize: 16,
  },
});
export default App;

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

To run the project on an Android Virtual Device or on real debugging device

react-native run-android

or on the iOS Simulator by running (macOS only)

react-native run-ios

Download Source Code

Output Screenshots

            

Output in Online Emulator

That was the example of React Native AutoComplete Input. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂


Related Posts

16 thoughts on “Example of React Native AutoComplete Input”

      • Thanks for your response, I found the reason , actually it’s working with autocomplete library version 3.6.0 but it has some issue with latest version of 4.0.+. I downgraded the library and its working now.

        Reply
  1. “react-native-autocomplete-input”: “^4.1.0”

    Show only () in overlay instead of movie names. Also on click of any of (), shows error undefined is not an object (evaluating ‘query.trim’)

    Reply
  2. Thanks Snehal for your reply.
    Somehow I got the overlay with list items properly in 4.1.0, but on click of it the overlay is not getting removed automatically. Any thoughts ?

    I am new to react native, I tried downgrading the version of autocomplete-input to 3.6.0 by changing in package.json. But it is not working. Looks like I am missing something.

    Reply
  3. hi, everything is working fine. but style is not working . I tried modifying both inputContainerStyle and containerStyle.

    i wanted a textbox style with just ” borderBottomWidth: 1 “, can you please let me know how to modify the “Autocomplete” textBox style.

    Thanks,

    Reply
  4. Hi I used it but the suggestion box is not floating over other inputs whereas it is pushing down other inputs to make a place for it self. Even I tried with position absolute and made it float then it is not clickable anymore

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.