Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Native: Display JSON Data in ListView

I want to display JSON-Data in a ListView. The Problem is, that the JSON data contains Dictionaries. In one Row I would like to display 'Gattung', 'ab' and 'bis'. I am not able to display following JSON-Data in a ListView:

[
{
    "Gattung": "ICE",
    "Zugummer": 26,
    "ab": "Regensburg Hbf",
    "bis": "Hanau Hbf",
    "Wochentag": "Fr",
    "Zeitraum": ""
},
{
    "Gattung": "ICE",
    "Zugummer": 27,
    "ab": "Frankfurt(Main)Hbf",
    "bis": "Regensburg Hbf",
    "Wochentag": "So",
    "Zeitraum": ""
},
{
    "Gattung": "ICE",
    "Zugummer": 28,
    "ab": "Regensburg Hbf",
    "bis": "Würzburg Hbf",
    "Wochentag": "Fr",
    "Zeitraum": ""
},
{
    "Gattung": "ICE",
    "Zugummer": 35,
    "ab": "Hamburg Hbf",
    "bis": "Puttgarden",
    "Wochentag": "tgl.",
    "Zeitraum": "25.06. - 04.09."
},
{
    "Gattung": "ICE",
    "Zugummer": 36,
    "ab": "Puttgarden",
    "bis": "Hamburg Hbf",
    "Wochentag": "tgl.",
    "Zeitraum": "25.06. - 04.09."
}
]

This is my code now:

 var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});


var MainView = React.createClass ({





  getInitialState() {

     return {

        jsonURL: 'http://demo.morgenrot-wolf.de/qubidu/test.json',
        dataSource: ds.cloneWithRows(['row 1', 'row 2']),
     }
   },



   componentDidMount(){

      this.loadJSONData();

   },



   loadJSONData() {

     fetch(this.state.jsonURL, {method: "GET"})
     .then((response) => response.json())
     .then((responseData) =>
     {
          for (var i = 0; i < responseData.length; i++)
          {


              this.setState({ dataSource: this.state.dataSource.cloneWithRows(responseData[i]) });
          }

     })
     .done(() => {


     });


   },




  render() {
    return (

      <View style={styles.container}>

         <ListView
              dataSource={this.state.dataSource}
              renderRow={(rowData) => <Text>{rowData}</Text>}
            />
      </View>

    );
  }
});
like image 572
profidash_98 Avatar asked Dec 19 '22 14:12

profidash_98


1 Answers

rowData is an object, so renderRow property of your list should look something like

renderRow: function(rowData) {
  return (
    <View style={styles.row}>
      <Text>{rowData.Gattung}</Text>
      <Text>{rowData.ab}</Text>
      <Text>{rowData.bis}</Text>
    </View>
  );
}

Also it is bad idea to call setState inside a loop. If reponseData is an array, this.setState({ dataSource: this.state.dataSource.cloneWithRows(responseData)}); should be enough.

Check this sample: https://rnplay.org/apps/4qH1HA

like image 162
Konstantin Kuznetsov Avatar answered Jan 11 '23 13:01

Konstantin Kuznetsov