How to loop in React JSX
Today we will show you how to loop in React JSX. In this article, we will show you two different methods to loop in the React component.
Checkout more articles on ReactJS
Ways to loop in React component JSX
1. Using for loop
Let’s assume that we have a list of items in the form of an array. Using the for loop, we can create a loop and then add a JSX element to an array.
1 2 3 4 5 6 | const arr = ['A', 'B', 'C', 'D', 'E', 'F']; const items = []; for (const [index, value] of arr.entries()) { items.push(<li key={index}>{value}</li>); } |
Now, we can embed the items
array by wrapping it in curly braces.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | render() { const arr = ['A', 'B', 'C', 'D', 'E', 'F']; const items = []; for (const [index, value] of arr.entries()) { items.push(<li key={index}>{value}</li>); } return ( <ul> {items} </ul> ) } |
2. Using map function
We can do the same directly in the JSX component, using the map
function instead of a for-of loop.
1 2 3 4 5 6 7 8 9 10 11 | render() { const arr = ['A', 'B', 'C', 'D', 'E', 'F']; return ( <ul> {arr.map((index, value) => { return <li key={index}>{value}</li> })} </ul> ) } |
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! đŸ™‚