For loop in react render method

JavascriptReactjs

Javascript Problem Overview


I want create paging link for my grid.I pass maxPages(number) property to component but i cant use for in render method. What can i do ?

var Pagination = React.createClass({

render: function(){
  

    return(
    <div class="text-center">
        <ul class="pagination">

            <li><a href="#">«</a></li>
            {for (var i=0;i <10;i++;)
            {
              return( <li><a href="#">i + 1 </a></li>);
            }
            }
         
            <li><a href="#">»</a></li>
        </ul>
    </div>);

}});

Javascript Solutions


Solution 1 - Javascript

You can run the loop before the rendering (note that there's an error in your for loop)

var lis = [];

for (var i=0; i<10; i++) {
    lis.push(<li><a href="#">{i + 1}</a></li>);
}

var Pagination = React.createClass({
    render: function(){
        return(
            <div class="text-center">
                <ul class="pagination">

                    <li><a href="#">«</a></li>
                    {lis}
                    <li><a href="#">»</a></li>
                </ul>
            </div>
        );
    }
});

FIDDLE

Solution 2 - Javascript

You can only embed expressions into JSX.

<ul className="pagination">{children}</ul>

is converted to something like

React.createElement('ul', {className: 'pagination'}, children);

Do you see now how you could never have a for loop in place of children? Statements cannot be inside a function call expression.

You can create an array beforehand, like adeneo showed in their answer.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1924375View Question on Stackoverflow
Solution 1 - JavascriptadeneoView Answer on Stackoverflow
Solution 2 - JavascriptFelix KlingView Answer on Stackoverflow