Explain Codes LogoExplain Codes Logo

Loop inside React JSX

javascript
jsx
react
performance
Alex KataevbyAlex Kataev·Feb 28, 2025
TLDR

Quick and dirty way, render a list in React JSX by using the .map() function:

{data.map(item => <div key={item.id}>{item.name}</div>)}

Remember to always use key for optimal rendering. Don't use .forEach() as it does not return a new array. On the other hand, .map() does (look who's the good guy here!).

map() in action: Rendering lists in JSX

First things first: we use .map() to iterate over arrays and transform each item into a JSX element:

{/* Superheroes in your application, because why not? */} {superheroes.map(hero => <Hero key={hero.id} name={hero.name} />)}

The reason .map() is so popular amongst React developers:

  • Declarative: .map() is readable and fits right into the React paradigm.
  • Immutable: Unlike other loops, .map() does not change the original array.

The importance of keys in rendering

Every JSX element in your map should have a distinct key prop, which helps React update the DOM efficiently:

{/* These keys unlock high performance rendering! */} {users.map(user => <User key={user.id} data={user} />)}

Rendering dynamic lengths and dealing with array initialization

In bizarre cases, when you have to generate a variable number of components, you can create an empty array with required length and map over it:

{/* Generating n empty seats for a spaceship flight to Mars */} {[...Array(n)].map((_, index) => <Seat key={index} />)}

Or by using Array.from:

{/* For the Martians returning home👽 */} {Array.from({length: n}).map((_, idx) => <Seat key={idx} />)}

Tackling undefined and null values

Before you .map(), make sure to .filter() out potential null or undefined values first:

{/* Gotta filter out null folks, Thanos might have been here */} {heroes.filter(Boolean).map(hero => <Hero key={hero.id} name={hero.name} />)}

Transpiling JSX to JavaScript using Babel

If you are curious about how JSX transpiles to JavaScript, play around on the Babel REPL tool and get to see how the JSX you write translates to JavaScript under the hood. It's like viewing the source code of the Matrix.

Boosting your React performance

Wanna go fast? Here are some tips:

  • React.memo can be used for components that you render using .map().
  • For lists of unknown length, prefill arrays using Array.from() or [...Array(n)].