Search code examples
javascriptreactjsflux

how to render through a simple for-loop in Reactjs?


I have a simple react component defined below

React.createClass({

generateContent:function(){

for(i = 1;i<=100;i++)

     if(i%2 == 0)
     {
        return <li>Even!</li>
     } 

 else{

      return <li>Odd!</li>

    }


},


render:function(){

   return  (<ul>
              {this.generateContent()}
            </ul>)


}


})

While Rendering, The component returns the first statement of the for loop(<li>Odd</li>) and then exits.

I'd like something like

<li>Odd</li>
<li>Even</li>
<li>Odd</li>
<li>Even</li>
....
...

How can i achieve this?


Solution

  • You need to push it all into an array:

    React.createClass({
        generateContent: function() {
            var html = [];
    
            for(i = 1;i<=100;i++) {
                if(i%2 == 0) {
                    html.push(<li>Even!</li>);
                } else {
                    html.push(<li>Odd!</li>);
                }           
            }
    
            return html;
        },
        render: function() {
            return (<ul>
                {this.generateContent()}
            </ul>);
       }
    });