51

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

}});
user1924375
  • 10,581
  • 6
  • 20
  • 27

2 Answers2

36

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

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 1
    Note that putting components outside of render and then using them in render will break some things in 0.13 (0.14 is changing this). – Brigand Apr 25 '15 at 03:24
10

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.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    And strangely enough, running `map` works because it returns an array -> https://jsfiddle.net/adeneo/69z2wepo/7038/ – adeneo Apr 25 '15 at 00:15
  • 1
    Yes, because `Array(10).join().split(',').map(...)` is an expression :) `React.createElement('ul', {className: 'pagination'}, Array(10).join().split(',').map(...));` is not a syntax error. – Felix Kling Apr 25 '15 at 00:15
  • Aha, so `createElement` accepts a single child, an array of children or text content, and any expression returning one of those are valid. – adeneo Apr 25 '15 at 00:18
  • This JSX converting stuff is clever ! – adeneo Apr 25 '15 at 00:20
  • 2
    It is! It's just the right amount of magic :) (my personal opinion) – Felix Kling Apr 25 '15 at 00:21