Mapping Arrays to JSX Elements in React
In React, a common requirement is to render a list of items. This can be achieved by mapping arrays to JSX elements.
Consider an array of strings:
const fruits = ['Apple', 'Banana', 'Cherry'];
To render these as a list, we use the JavaScript map
function. Each item in the array becomes a JSX element:
{fruits.map((fruit) =>
<li key={fruit}>{fruit}</li>
)}
Here, each fruit
in the fruits
array is passed to an arrow function, which returns a JSX <li>
element. The key
prop is essential when creating lists in React because it helps React identify which items have changed, are added, or are removed.
The output will be:
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
This technique allows you to dynamically render lists or grids in your React applications.
Explore more articles
Keep experimenting and happy coding! You can find me at @samuellawrentz on X.