Create loop inside React JSX

While playing with React I needed to create a loop to print a defined number of items. I was surprised that using JSX it wasn't very intuitive how to do so. After some Googling, this is what I found.

The magic map function will accept an empty array of your defined length. In my case, 7.

Array.apply(null, Array(7)).map(function(item, i) {}
Code language: JavaScript (javascript)

When using it inside a React component it looks like this:

var MyComponent = React.createClass({ render:function(){ return ( <div> {Array.apply(null, Array(7)).map(function(item, i){ return ( <div> This will print the counter {i} </div> ); }, this)} </div> ); } });
Code language: PHP (php)

Do you know of a simpler way of creating a loop, such as a for, inside a React component?

About Ricard Torres

Senior Front-end Software Engineer at Netcentric, from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

3 comments
  • Nice googling xD

  • Try

    {Array.apply(null, Array(count)).map((item, i) => This will print the counter {i} )}
    Code language: JavaScript (javascript)
  • Actually, i am a problem related to this issue, since i need the for loop in my render method, and this is not possible

    render() { return( {for( let i = 0; i<3; i++) { console.log(i) } } )}
    Code language: JavaScript (javascript)

    for example this code is not acceptable in JSX

Leave a Reply

Add <code> Some Code </code> if you need to.

*
*