Clue Mediator

How to loop in React JSX

๐Ÿ“…October 9, 2021
๐Ÿ—ReactJS

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
  2. Using map function

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.

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.

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.

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..!! ๐Ÿ™‚