kirkegaard
kirkegaard

Reputation: 1138

Populate list items from json in React component

I'm new to reactjs and i have a json object that i want to iterate through and populate list items in a react component. I get the json from server with an ajax call..

My ajax inside getData() method:

  $.ajax(
        {
            type: 'get',
            url: url,
            success: function (data) {
                this.setState({ data: JSON.parse(data) })  //or parse
            }.bind(this)
        },

    );

Constructor:

constructor() {
    super();
    this.state = {
        data: null
    };

    this.getData = this.getData.bind(this);
  }

Data looks like this:

{
    "commentID":25,
    "matchID":43234,
    "commentatorID":12537228724216704,
    "timeM":67,
    "timeRT":null,
    "action":"goal",
    "description":"aaaaaaaa"
},
{
    "commentID":27,
    "matchID":56,
    "commentatorID":12537228724216704,
    "timeM":14,
    "timeRT":null,
    "action":"",
    "description":"fgfafafaaffaafasfasf"
},

What i've already tried is to stringify the object but when i try to iterate through the string, it's alot of work when i only want to list "description" and "timeM" .

Should i run through the json object in the render method and create list items or are there other ways to do it? I'm looking for a good example on how to do this. Thanks!

Upvotes: 2

Views: 22743

Answers (1)

user5490729
user5490729

Reputation:

To understand which react component life-cycle events one should setState in, you could refer to https://facebook.github.io/react/docs/react-component.html

to create the new array, you could simply

this.setState({
    data: resoponseArray.map(item => {description: item.description, timeM: item.timeM})
})

Edit

and to render you data

render () {
    return(
        <div>
            <ul>
                {
                    this.state.data.map((item, key) => {
                        return <li key={key}>{item.timeM} {item.description}</li>
                    })
                }
            </ul>
        </div>
    )
}

Upvotes: 2

Related Questions