3

I am trying to render in react, jsx, a loop inside of a loop Like bellow:

{this.state.ans.map(function(item) {
    return (
        {this.state.quest.map(
            function(item1) {return (item1)}
        )}        
        {item}
    )
})}

This does not work any other suggestions

1
  • Is that everything inside the render? What are you trying to return in the end? Usually you want to do all the loops and return the result of all the loops at the end. Commented Dec 4, 2017 at 11:59

2 Answers 2

2

You forgot the wrapping div in your first map statement:

render() {
  return (
    <div>
      {this.state.ans.map(item =>
        <div> // this div was missing
          {this.state.quest.map(quest => quest)}
          {item}
        </div>
      )}
    </div>
  )
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great, yes that was the issue!
2

Try it like this:

render(){
    return (
        .
        .
        .
        {this.state.ans.map((item) => {
            return (
                <div>
                    {this.state.quest.map((item1) => { 
                           return (item1); 
                        }
                    )}        
                   {item}
               </div>
            );
        })}
    );
}

Basically the idea is that, you should return a single element - in my example a div (with the latest react version you don't have to). And moreover, use lambdas in order for this to reference the correct context.

If you do not use ES6, you can add the following statement at the beginning of the render method:

var that = this;

and use that afterwards with the function(){} syntax inside the return.

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.