5

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?

4 Answers 4

5

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>
    )
 })}
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

2

I have created a Snack here at: https://snack.expo.io/rk4f3aSnQ with the solution.

map function belongs to the Array Class so won't work on an Object.

I put the object in places.json file in the project. You will surely find a way to do so. Also, always return code as a single component while using react-native as you will notice in the App.js file this code snippet:

render() {
    return (
        <View style={styles.container}>
          {places.map((place) =>
              <View>
                <Text>{place.title}</Text>
                <Text>{place.description}</Text>
              </View>)}
        </View>
    );
  }

Comments

1

Another solution is to use the spread operator:

{[...places].map((place) => {
  return (
    <Text>{place.title}</Text>
    <Text>{place.description}</Text>
  )
})}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.