Reputation: 117
I'm trying to create a FlatList that contains an array with objects that has an array and I can't get it to work.
my error message:
“Invariant Violation: Object is not valid as a React child (found: object with keys {DATA, MESSAGE, STATUS}). If you meant to render a collection of children use an array instead ”
tho I can get it to work with a normal list like [1,2,3,4]
here's my code:
import React, { Component } from 'react';
import {StyleSheet, View, Text, StatusBar, TouchableOpacity, FlatList, ActivityIndicator } from 'react-native';
class FilterScreen extends Component {
state = {
data: [{"DATA":[{"filter_id":"44","filter_name":"filter 1"},{"filter_id":"45","filter_name":"filter 2"},{"filter_id":"46","filter_name":"filter 3"},{"filter_id":"47","filter_name":"filter 4"},{"filter_id":"48","filter_name":"filter 5"}],"MESSAGE":"DATA FOUND","STATUS":200}],
}
renderRow = ({item}) => {
return (
<View style={styles.item}>
<Text>{item.DATA.filter_name}</Text> // my error points to this line
</View>
)
}
render() {
return (
<View style={styles.MainContainer}>
<FlatList
data={this.state.data}
renderItem={this.renderRow}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer: {
marginTop:50,
},
});
export default FilterScreen;
I want my FlatList to print out the filter_name, like this
filter 1
filter 2
filter 3
filter 4
filter 5
Upvotes: 0
Views: 2511
Reputation: 10709
You need to be careful on how your data is structured. Your this.state.data
is an array. Inside your array you have two objects. A DATA
and a MESSAGE
object. So if you want to pass the DATA
object to renderItem, you have to pass this.state.data[0].DATA
, like here:
<View style={styles.container}>
<FlatList
data={this.state.data[0].DATA}
renderItem={this.renderRow}
keyExtractor={(item, index) => index.toString()}
/>
</View>
Then you need to adapt your renderItem function to:
//remove the comment inside return, otherwise you will get again an error
renderRow = ({item}) => {
return (
<View style={styles.item}>
<Text>{item.filter_name}</Text>
</View>
)
Working example: https://snack.expo.io/BkmD4V12V
Upvotes: 2