Loop inside React JSX
Quick and dirty way, render a list in React JSX by using the .map()
function:
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:
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:
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:
Or by using Array.from
:
Tackling undefined
and null
values
Before you .map()
, make sure to .filter()
out potential null
or undefined
values first:
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)]
.
Was this article helpful?