Looping Json & Display in React Native

12,248

React can render an array of Elements, so you just need to construct an array and assign it to your contents variable. I made an example using map.

render: function() {
     console.log(this.state.list);
     contents = this.state.list.results.map(function (item) {
        return (
          <View key={item.user.email} style={ styles.content }>
            <Text>{item.user.email}</Text>
          </View>
        );
     });
     return (
      <View style={ styles.container }>
        <View style={ styles.header }>
        <Text style={ styles.headerText }>XXX</Text>
        </View>
        <View style={ styles.content }>
            { contents }
        </View>
      </View>
    );
  }

And also: when you have an array of elements in React, you should provide a unique key attribute to each element in the array. See why. In this case, I use item.user.email as the unique identifier, but you can use another attribute, just make sure it unique (item.user.md5 is promising)

Share:
12,248
CodeGuru
Author by

CodeGuru

Startups , Startups &amp; Startups. Failure , Failure &amp; Failure. I'm not giving up.

Updated on June 21, 2022

Comments

  • CodeGuru
    CodeGuru almost 2 years

    How do I go about looping the result i retrieved from Json? enter image description here

    render: function() {
         console.log(this.state.list);
         contents = (
          <View style={ styles.content }>
            <Text>Loaded</Text>
    
          </View>
         )
         return (
          <View style={ styles.container }>
            <View style={ styles.header }>
            <Text style={ styles.headerText }>XXX</Text>
            </View>
            <View style={ styles.content }>
                { contents }
            </View>
          </View>
        );
      }
    
  • Tony Dinh
    Tony Dinh over 8 years
    Make sure the this.state.list object always has results array in it. You could add more logic to handle your state or just add if/else condition to get your desired contents.
  • CodeGuru
    CodeGuru over 8 years
    i initialised by using list: {results:[]} at getInitialState
  • CodeGuru
    CodeGuru over 8 years
    but i'm getting warning : each child in an array or iterator should have a unique key prop, please advice :)
  • Tony Dinh
    Tony Dinh over 8 years
    That was my mistake not putting the key attribute. Check my updated answer.