1

How do I loop this props?

enter image description here

Tried looping something like this:

for (var key in this.props.data.data) {

    this.state.newData.push(
        <NewData key={key} />
    );
}

doesn't work.

2 Answers 2

1

you have to use setState to change the state:

var newArr = [];
for (var key in this.props.data.data) {
    newArr.push(<NewData key={key} />);
}
this.setState( {newData: newArr });
Sign up to request clarification or add additional context in comments.

Comments

1

Something like this ought to work:

const newData = this.props.data.data.map(key => (<NewData key={key} />));
this.setState({ newData });

Two notable changes:

  1. Using Array.prototype.map to iterate over the array rather than a for-in loop.
  2. Using setState to set the state rather than doing so directly. Outside of the constructor, you should always use setState. See https://facebook.github.io/react/docs/state-and-lifecycle.html for more details.

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.