0

Suppose, I'm getting JSON array and want to setState as I'm getting that array in my component.

        for( var follower_id = 0; follower_id < followers_data.length; follower_id++) {
          this.setState({
            followers_data_username[followers_data_username.length] = followers_data[follower_id].login
          });
          console.log(followers_data_username[0]);
        }

But I don't know how to set up my getInitialState if I'm going to use an array. Also, I don't think that I can setState of an array.

I'm new to React. So, any help or pointing to the right direction would be highly appreciated.

Consider the JSON to be something similar to this: https://api.github.com/users/ghoshnirmalya/followers

4
  • why are you trying to set a state for each element in the json array? that is just going to override any data from the previous row... are you trying to list out a table on the front end? Commented Nov 11, 2015 at 8:01
  • yes. i'm trying to get all the data from the json and list out a table. what will be the best way to do that? Commented Nov 11, 2015 at 8:02
  • is this es6 syntax? did you look at the react examples? Commented Nov 11, 2015 at 8:03
  • I'm trying to follow the syntax which is provided in the react tutorial (facebook.github.io/react/docs/tutorial.html). Commented Nov 11, 2015 at 8:05

1 Answer 1

1

you should use a map function on your data like so

render(){
    let rows = this.state.followers_data.map( (follower, i) => <TableRow follower={follower} key={i} />);

    return (
        <table>
            <tbody>{rows}</tbody>
        </table>
    );
}

and your row component would look something like this..

const TableRow = (props) => {
    return (
        <tr>
            <td>{this.props.follower.login}</td>
        </tr>
    );
};

now this is just a basic example... you need to model it to work for your project.. but you should follow this pattern for all of the json data... you have a table and in the tbody you render rows.. which is an array of components that are generated off of each json object in the array.

Sign up to request clarification or add additional context in comments.

2 Comments

What if I'm loading the JSON from another url using onClick function? Will this work for that scenario also?
@NirmalyaGhosh yes that is what I was expecting you to have.. your onClick function should call this.setState({followers_data: whatever_your_data_is}) which will re-render the rows with whatever the data is that comes back

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.