souldeux souldeux - 3 months ago 12
React JSX Question

How to render an element (React Class) an arbitrary number of times?

I have two components:

var kBoard = React.createClass({
getInitialState: function() {
return {numCols: 0};
},
componentDidMount: function(){
//simplified
this.setState({numCols: 3});
},
render: function () {
return(
<div className="kBoard">
I'm a board
//TODO: insert columns
</div>
);
}
});

var kColumn = React.createClass({
render: function() {
return (
<div className='kColumn'>
I'm a column
</div>
);
}
});


Where it says
//TODO: insert columns
, I want to insert a number of
Column
components equal to
this.state.numCols
.

I tried a simple for loop, but after learning more about how JSX compiles to JS I understand why that won't work. I feel like I should probably be using
map
somehow, but I haven't been able to get it right yet.

Answer

React accepts an array of elements, so you can create it using a for or while loops, or Array.prototype.map. You can also use Array.from to create a new array of length x, and populate it with columns:

render: function () {
    return(
        <div className="kBoard">
            I'm a board
            {
                Array.from({ length: this.state.numCols }, (v, k) => <kColumn key={ k } />)
            }
        </div>
    );
}

Note react components name should start with a capital case - kColumn -> KColumn.

Comments