Reputation: 1735
I have the below code to loop through an array.
export default function App() {
const [x, setX] = useState([
{name:'a'},{name:'b'}
]);
return (
<View >
<FlatList
data={x}
renderItem={(item) => {
return <Text>{item.name}</Text>;
}}
/>
</View>
);
The above code gives below error
Warning: Failed child context type: Invalid child context `virtualizedCell.cellKey` of type `number` supplied to `CellRenderer`, expected `string`.
When I change
<FlatList
data={x}
renderItem={(item) => {
return <Text>{item.name}</Text>;
}}
/>
To
<FlatList
data={x}
renderItem={({item}) => {
return <Text>{item.name}</Text>;
}}
/>
The code is correct now and it works, see I changed (item) to ({item}) added curly braces .
Why is so ?
Upvotes: 0
Views: 942
Reputation: 2104
As you can see link document https://reactnative.dev/docs/flatlist.html renderItem
renderItem({ item, index, separators });
Example usage:
<FlatList
ItemSeparatorComponent={
Platform.OS !== 'android' &&
(({ highlighted }) => (
<View
style={[
style.separator,
highlighted && { marginLeft: 0 }
]}
/>
))
}
data={[{ title: 'Title Text', key: 'item1' }]}
renderItem={({ item, index, separators }) => (
<TouchableHighlight
key={item.key}
onPress={() => this._onPress(item)}
onShowUnderlay={separators.highlight}
onHideUnderlay={separators.unhighlight}>
<View style={{ backgroundColor: 'white' }}>
<Text>{item.title}</Text>
</View>
</TouchableHighlight>
)}
/>
Upvotes: 2
Reputation: 544
you should use the key prop flour. try again with the code below
<FlatList
data={x}
renderItem={({ item, index }) => (
<Text key={index}>{item.name}</Text>
)}
keyExtractor={(item, index) => index.toString()}
/>
Upvotes: 2
Reputation: 178
Because the FlatList
returns item object in which their is your items or array to be render!
its like
{
items: {
{name:'a'},
{name:'b'}
}
}
so we have to go to item first by destructuring by {item} and then access the inner objects.
Hope it will make understanding !
Upvotes: 0