Reputation: 237
I'm trying to use Autocomplete in React-native but I'm obviously doing something wrong.
Here a minimal example of code showing what I'm doing:
import React, {useState, useEffect} from 'react';
import {
SafeAreaView,
StyleSheet,
TextInput,
Text,
TouchableOpacity,
View,
} from 'react-native';
import Autocomplete from 'react-native-autocomplete-input';
const DATA =
[{"id": 1,"title": "test1"},{"id": 2,"title": "test2"},{"id": 3,"title": "test3"}]
const App = () => {
const [query, setQuery] = useState('');
return (
<SafeAreaView style={{flex: 1}}>
<View style={styles.container}>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
data={DATA}
value={query}
onChangeText={setQuery}
renderItem={({item}) => (
<TouchableOpacity
onPress={() => {}}>
<Text>
{item.title}
</Text>
</TouchableOpacity>
)}
/>
</View>
</SafeAreaView>
);
};
I reduced the code to the very minimum.
However, I keep getting error: "Objecs are not valid as a React child (found: object with keys {id,title}"
It seems I'm missing something very obvious about renderItem (I guess), but since I'm stuck since a few hours, another eye could spot what I'm doing wrong.. any help would be appreciated, thanks.
Upvotes: 2
Views: 1577
Reputation: 237
I actually found the answer.
It seems, I haven't read correctly the list of props for Autocomplete: in fact, renderItem must be passed inside an option called "flatListProps".
Correct code is below:
import React, {useState, useEffect} from 'react';
import {
SafeAreaView,
StyleSheet,
TextInput,
Text,
TouchableOpacity,
View,
} from 'react-native';
import Autocomplete from 'react-native-autocomplete-input';
const DATA =
[{"id": 1,"title": "test1"},{"id": 2,"title": "test2"},{"id": 3,"title": "test3"}]
const App = () => {
const [query, setQuery] = useState('');
return (
<SafeAreaView style={{flex: 1}}>
<View style={styles.container}>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
data={DATA}
value={query}
onChangeText={setQuery}
flatListProps={{
keyboardShouldPersistTaps: 'always',
keyExtractor: (item) => item.id,
renderItem: ( ({item}) => (
<TouchableOpacity
onPress={() => {}}>
<Text>
{item.title}
</Text>
</TouchableOpacity>
))
}}
/>
</View>
</SafeAreaView>
);
};
Upvotes: 1
Reputation: 114
renderItem={({ item, i }) => (
<TouchableOpacity key={i} onPress={() => ()}>
<Text>{item.label}</Text>
</TouchableOpacity>
)}
You have to pass the index to key.
Upvotes: 0
Reputation: 22500
Your destructuring was wrong. do like below {id,title}
. renderItem
is array of iteration so its look like object.
renderItem={({title,id}) => (
<TouchableOpacity
onPress={() => {}}>
<Text>
{title}
</Text>
</TouchableOpacity>
)}
Upvotes: 1