Reputation: 109
I want to display Json Data in a Flatlis component in my react-native App, but i can't figure out how to display it. I want to show the name of the dinosaur in a List and if i press on the list item i want to show the dimensions of the dinosaur. I have the List items and the Detail screen all set up, but i get a blank screen with this code, did I import the JSON data in a wrong way or do i somehow have to restructure the data to display it?
I have JSON data like this:
{
"lambeosaurus": {
"dimensions": {
"height": 2.1,
"length": 12.5,
"weight": 5000
}
},
"stegosaurus": {
"dimensions": {
"height": 4,
"length": 9,
"weight": 2500
}
}
}
and this is my Code:
import React from 'react'
import { StyleSheet, Text, View, TouchableOpacity, StatusBar, FlatList, Image } from 'react-native'
import MyListItem from '../components/MyListItem'
const data = require("../data/MockData.json")
class HomeScreen extends React.Component {
render() {
return (
<View>
<StatusBar hidden={true} />
<FlatList
data={data}
renderItem={({ item }) =>
<MyListItem
item={item}
onPress={() => {
this.props.navigation.navigate('Details', {
item: item
})
}}
/>
}
/>
</View>
);
}
}
export default HomeScreen;
Upvotes: 2
Views: 2596
Reputation: 112787
FlatList
expects an array as data
prop, but your JSON is an object. You could change it into an array before using it.
// const objData = require("../data/MockData.json");
const objData = {
lambeosaurus: {
dimensions: {
height: 2.1,
length: 12.5,
weight: 5000
}
},
stegosaurus: {
dimensions: {
height: 4,
length: 9,
weight: 2500
}
}
};
const data = Object.keys(objData).map(key => ({
key,
...objData[key]
}));
console.log(data);
Upvotes: 2