2 ways to loop through a number in React
In this article, we will discuss 2 ways how you can loop through a number in React.
While developing frontend of an application 🖥, you might encounter a situation where you have to display a list of data. For example, a list of users etc.
Most common way to loop through an array in React is using Javascript built-in map function.
But if you have a number that you have to loop through. For example, run a loop till 10 etc.
In this case, we have 2 options.
1st way: Using function ☑️
One way to loop through a number in React is to create a function that will:
- Create an array.
- Using basic for loop and push the HTML code in array.
- Return the array.
Here is the code on how to do that. 👨🏻💻
function App() {
const [number, setNumber] = React.useState(10);
function renderLoop() {
const elements = [];
for (let a = 0; a < number; a++) {
elements.push(
<p key={ `1st-way-${ a }` }>{ a }</p>
);
}
return elements;
}
return (
<>
{ renderLoop() }
</>
);
}
Following will be the output of above code:
0
1
2
3
4
5
6
7
8
9
2nd way: Using map ✅
Javascript’s map function can also be used to iterate over an array and display a list without having to create a function.
function App() {
const [number, setNumber] = React.useState(10);
return (
<>
{ Array.from({ length: number }, function (_, index) { return index })
.map(function (n) {
return (
<p key={ `2nd-way-${ n }` }>{ n }</p>
)
}) }
</>
);
}
Explanation 🕵🏻♂️
- The first argument of Array.from is an object that will create an array of length 10 such that each element has an index starting from 0.
- The second argument is a mapping function.
- First parameter is “_” which means the value.
- Second parameter is “index”.
- It is returning the index without any modification, so the original number will be returned.
- It will create an array from 0 to 9.
- Using the map function, you can perform some action on that array created from number. In this case, we are displaying each number n in a paragraph. 📄
So that’s how you can loop through a number in React. If you face any problem in following this, kindly do let me know. 💬