How to write loops in React
By Tom Hastjarjanto and Editors
Introduction
In this post I will show you how to write loops in React. I will show you how to write loops in React using the map function and I will show you how to write loops in React using the for loop.
Write loops in React using map
The map function is used to loop over an array in React. In this example I will show you how to write loops in React using the map function.
import React from "react";
export default function LoopsInReact() {
const data = [
{ id: 1, title: "Buy milk", completed: false },
{ id: 2, title: "Buy bread", completed: true },
{ id: 3, title: "Buy eggs", completed: false },
];
return (
<div className="App">
<ul>
{data.map((item) => (
<li key={item.id}>
{item.title} {item.completed ? "✅" : "❌"}
</li>
))}
</ul>
</div>
);
}
Write loops in React using for loop
The for loop is used to loop over an array in React. In this example I will show you how to write loops in React using the for loop.
import React from "react";
export default function LoopsInReact() {
const data = [
{ id: 1, title: "Buy milk", completed: false },
{ id: 2, title: "Buy bread", completed: true },
{ id: 3, title: "Buy eggs", completed: false },
];
return (
<div className="App">
<ul>
{(() => {
const items = [];
for (let i = 0; i < data.length; i++) {
const item = data[i];
items.push(
<li key={item.id}>
{item.title} {item.completed ? "✅" : "❌"}
</li>
);
}
return items;
})()}
</ul>
</div>
);
}
The key
attribute
The key
attribute is used to identify each element in a list. React uses the key
attribute to identify which items have changed, are added, or are removed. The key
attribute is required when using the map function.
Conclusion
In this post I showed you how to write loops in React. I showed you how to write loops in React using the map function and I showed you how to write loops in React using the for loop.
Further reading
Tom Hastjarjanto has been using React.js since 2015. Connect with him at Twitter or LinkedIn.