Reputation: 2373
Normally, I am able to render an array of objects in a Flatlist but for some reason this time I cannot. I am getting an error, "Invariant Violation: Objects are not valid as a React child..." Does anyone know why this is happening?
<FlatList
data={allergins}
keyExtractor={(allergin, index) => index}
renderItem={({allergin}) => (
this.renderAllergins(allergin)
)}
/>
Upvotes: 0
Views: 486
Reputation: 267
For me, the toString
or JSON.stringify()
did not work, as i needed to pass the object which contained images as well.
So i did very simple thing:
I put the {item}
within <View></View>
tag.
<FlatList
data={allergins}
keyExtractor={(allergin, index) => index}
renderItem={({allergin}) => (
<View>this.renderAllergins(allergin)</View> . //You can try it as well
)}
/>
Upvotes: 0
Reputation: 884
So, it seems you are trying to render an object inside a Text. It is only going to accept strings/numbers as children. So what you have to do is:
If you have a know object structure, which seems to be the case, this.renderAllergins
should look something like:
renderAllergins = allergin => (
<View>
<Text>{allergin.name}</Text>
<Text>{allergin.value}</Text>
</View>
)
The other option is rendering every key in the object. You would do that similar to this:
renderAllergins = allergin => (
<View>
{Object.keys(allergin).forEach((key, value) => (
<Text>{value}</Text>
))}
</View>
)
Upvotes: 0
Reputation: 9458
As I said in my comments, FlatList
is not the issue. The issue is <Text>{ allergins }</Text>
.
You can either:
Stringify allergins
(inline)
<Text>{ JSON.stringify(allergins) }</Text>
Map out the array
allergins.map(allergin => <Text>{ allergin.name }</Text>)
You cannot render an object (i.e. { name: "Soy", value: "Free From" }
) in React. Valid children are strings, numbers, booleans, other elements/components, and arrays (of these types).
Upvotes: 2