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

852 Views Asked by At

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?

4

There are 4 best solutions below

0
On BEST ANSWER

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>);
   }
});
0
On
React.createClass({

    render: function(){
        var html = [];
        for (var i = 1; i <= 100; i++) {
            if (i % 2 === 0) {
                html.push(<li key={i}>Even</li>);
            } else {
                html.push(<li key={i}>Odd</li>);
            }
        }

        return  <ul>{html}</ul>;
    }
})
0
On

You can push all the items to an array and then return it:

React.createClass({

generateContent:function(){
    var list = [];
    var content = ['Even!','Odd!'];
    for(i = 1;i<=100;i++){
       list.push(<li>{content[i%2]}</li>)
    }

    return list;    
},


render:function(){

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


})
0
On

When you call generateContents(), you're returning on the first iteration, so you only get one <li>. You should create a list of elements instead - the loop will terminate for you when it reaches <= 100.

http://output.jsbin.com/jomiqututo

For example:

var MyComponent = React.createClass({
    generateContent: function() {
        var html = [];
        for(var 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>
        );
    }
});