How to Loop Inside React JSX
In this tutorial I would like to talk about different ways of performing loops inside JSX code. Hopefully it will be helpful to you when you create some cool stuff for Gutenberg.
Let’s begin with a simple ordered list.
const shoppingCart = [ 'coffee', 'avocado', 'bread' ]
return (
<ol>
{shoppingCart.map((item, index) => {
return <li>{item}</li>
})}
</ol>
)
A shorthand way of doing this:
return (
<ul>
{shoppingCart.map((item, index) => <li>{item}</li>}
</ul>
)
This loop can also be easily performed for objects:
const shoppingCart = [
{ id : 124, name : 'coffee' },
{ id : 456, name : 'avocado' },
{ id : 789, name : 'bread' },
]
return (
<select>
{shoppingCart.map((item, index) => {
return <option value={item.id}>{item.name}</option>
})}
</select>
)
There is also possible to use for
loops.
const shoppingCart = [ 'coffee', 'avocado', 'bread' ]
const productList = []
for( const [i, item] of shoppingCart.entries() ) {
productList.push( <li>{item}</li> )
}
return(
<ol>{productList}</ol>
)
Using objects is also useful when you got a notice in your browser console “Warning: Each child in a list should have a unique key
prop.” – in this case you can use id
property as a key attribute of every <li>
element.
const shoppingCart = [
{ id : 124, name : 'coffee' },
{ id : 456, name : 'avocado' },
{ id : 789, name : 'bread' },
]
const productList = []
for( const [i, item] of shoppingCart.entries() ) {
productList.push( <li key={ item.id }>{ item.name }</li> )
}
return(
<ol>{productList}</ol>
)

Misha Rudrastyh
Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.
Need some developer help? Contact me