Loop inside of a loop, in React JSX

All we need is an easy explanation of the problem, so here it is.

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

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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>
  )
}

Method 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.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply