How to Loop and Repeat a JSX Element X Number of Times in React
Table of Contents
React's use of JSX allows you to write HTML-like code in JavaScript.
Because it is JavaScript, you can use JavaScript to repeat elements in JSX, wheres you couldn't do this normally in HTML.
In this post, we'll learn the easiest way to repeat JSX elements in a loop in React.
How to repeat JSX elements in a loop
Let's say you have an array of objects, and you want to repeat JSX elements for each object in the array.
First, we can define the array:
JAVASCRIPTconst array = [
{ name: "John", age: 20 },
{ name: "Mary", age: 25 },
{ name: "Peter", age: 30 },
];
Then, we can use the map()
method to loop through the array and create a JSX element for each object in the array:
JSXconst array = [
{ name: "John", age: 20 },
{ name: "Mary", age: 25 },
{ name: "Peter", age: 30 },
];
const elements = array.map(item => {
return (
<div>
<h1>{item.name}</h1>
<p>{item.age}</p>
</div>
);
});
Finally, we can render the JSX elements by calling it inside using { elements }
:
JSXconst array = [
{ name: "John", age: 20 },
{ name: "Mary", age: 25 },
{ name: "Peter", age: 30 },
];
const elements = array.map(item => {
return (
<li>
<h1>{item.name}</h1>
<p>{item.age}</p>
</li>
);
});
const App = () => {
return (
<div>
<h1>Hello World</h1>
<ul>
{ elements }
</ul>
</div>
);
}
This code results in this HTML:
HTML<div>
<h1>Hello World</h1>
<ul>
<li>
<h1>John</h1>
<p>20</p>
</li>
<li>
<h1>Mary</h1>
<p>25</p>
</li>
<li>
<h1>Peter</h1>
<p>30</p>
</li>
</ul>
</div>
Here's how you add a key to each JSX element:
JSXconst array = [
{ name: "John", age: 20 },
{ name: "Mary", age: 25 },
{ name: "Peter", age: 30 },
];
const elements = array.map(item => {
return (
<li key={item.name}>
<h1>{item.name}</h1>
<p>{item.age}</p>
</li>
);
});
Conclusion
In this post, we learned how to repeat JSX elements in a loop in React.
Simply use the map()
method to loop through an array and create a JSX element for each object in the array.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Getting Started with Express
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- Getting Started with Deno
- Getting Started with Sass
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase