souldeux
souldeux

Reputation: 3755

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.

Upvotes: 1

Views: 868

Answers (3)

Ori Drori
Ori Drori

Reputation: 191976

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.

Upvotes: 2

Shahid Ahmad
Shahid Ahmad

Reputation: 774

Try This

var kBoard = React.createClass({
getInitialState: function() {
    return {numCols: 0};
},
componentDidMount: function(){
    //simplified
    this.setState({numCols: 3});
},
render: function () {
    return(
        <div className="kBoard">
            {
               this.state.numCols.map(function(result,i) {
                 return <kColumn key={i} />;
               })
            }
            //TODO: insert columns
        </div>
    );
}
});

Upvotes: 0

Marco Scabbiolo
Marco Scabbiolo

Reputation: 7449

You can create an array where every element's value is it's index, and then map that to an array of columns, to get a new column for each index. Use the index property to set the key of the column

render: function () {

    var i= 0, arr = [];

    // Fill the array with the indexes
    for (i = 0; i < this.state.numCols; i += 1) {
        arr[i] = i;        
    }

    return(
        <div className="kBoard">
            I'm a board
            {arr.map(function(i) {
                return <kColumn key={i} />
            });}
        </div>
    );
}

Upvotes: 0

Related Questions