I'm developing an app in React Native and I have this JSON:
const places = {
"place1":{
"title":"title 1",
"image":"../img/image1.jpeg",
"description":"description 1.",
},
"place2":{
"title":"title 2",
"image":"../img/image2.jpeg",
"description":"description 2.",
}
};
I'd like to output it in a list of elements, I understood that to do this I have to use map() this is my code:
export default class App extends Component{
render() {
return (
<View style={styles.container}>
{places.map((place) => {
return (
<Text>{place.title}</Text>
<Text>{place.description}</Text>
)
})}
</View>
);
}
}
but it does not work, does anyone know what I'm wrong or how can I reach my goal?
Places is an object and you can't iterate like this. You have to get the keys with Object.keys and iterate through them instead. Like this.
Object.keys(places).map((key) => {
return (
<Text>{places[key].title}</Text>
<Text>{places[key].description}</Text>
)
})}
MAP function works on Array, not on object. Please update your const places as the following:
const places = [{
"title":"title 1",
"image":"../img/image1.jpeg",
"description":"description 1.",
},{
"title":"title 2",
"image":"../img/image2.jpeg",
"description":"description 2.",
}]
Thanks. Enjoy Coding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With