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 command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
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 = () => {
// For Main Data
const [films, setFilms] = useState([]);
// For Filtered Data
const [filteredFilms, setFilteredFilms] = useState([]);
// For Selected Data
const [selectedValue, setSelectedValue] = useState({});
useEffect(() => {
fetch('https://abooutreactapis.000webhostapp.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 every time 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}) => (
// For the suggestion view
<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
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
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. 🙂
Its not working , its only showing empty array ‘()’ while searching, suggest the required correction.
Hello saurav, I have cross checked twice but everything is fine with this example. Can you please share your code so that I can help you.
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.
This API have problem with Android Overflow. 🙁
Can you please describe more?
I have tried it with Android also but found no problem.
This API have problem with Android Emulator. İf i write something, the program are not getting the results like in iOS
What is the problem or warning it showing?
“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’)
I just want to quote Saurabh’s Comment “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.”
downgrading to 3.6.0 giving other error …
“invariant violation: listview has been removed from react native”
I think you are still doing some mistakes. As I have checked on 3.6.0 version.
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.
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,
Can you please share the snack(https://snack.expo.io/) or share the code you have tried on aboutreact11@gmail.com?
Hi Snehal, thanks for the reply here is my expo link https://snack.expo.io/r1EFfDDiB
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
Same problem here 🙁
Hi, everything works fine but Autocomplete pushes down other components. For example, I have a “Add” button right besides it and the list with suggestions pushes it down to the middle of the screen.
I’ve already tried to separate Autocomplete and the Button with fragments and tried to set autocompleteContainer to Absolute but that does not solves my problem.
Thanks
I Tried running on expo but it is throwing some error. Is this code correct? Should I follow this for a general idea ?
Not working on expo from direct link.
It is the error of web service, You can change any other web service to get the suggestion data for input.
Hi,
I am getting the error like this
Error: Objects are not valid as a React child (found: object with keys {userId, id, title, completed}). If you meant to render a collection of children, use an array instead.
could you help me to fix the issue
thanks