How to write for loops in React JSX

Tags: react, javascript
Published: 2021-08-19 11:03:03

In this tutorial, we will learn how to write loops inside JSX in React.

# Setting up the project

Let's create a new React app using the following command:

```bash
npx create-react-app react-for-loop
```

Let's add some styling to the page in `index.css`:

```css
body {
  margin: 10px auto;
}
.app {
  margin: 0;
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, 0%);
}
```

# Using the map function

In our application, let's display a list pizza toppings:

```jsx
const toppings = [
  "Golden Corn",
  "Paneer",
  "Tomato",
  "Mushroom",
  "Onion",
  "Black Olives",
]
function App() {
  return (
    <div className="app">
      <h2>Pizza Toppings</h2>
      <ul>
        {toppings.map(topping => {
          return <li>{topping}</li>
        })}
      </ul>
    </div>
  )
}

export default App
```

In the above code,

- We have declared a list of Pizza toppings (as you may have guessed, I am a vegetarian and can't even imagine pineapple as a topping 🤮)
- Inside the render function, we are using the [Javascript map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) function
  for looping the list.
- The map function accepts a callback, which receives the current item as the first argument (the name of the topping in our case).
  Then, we return the JSX that need to be rendered for each topping (a list item in our case).

# Adding key to the list

If you start the application, run it in the browser, and open the browser console, you will see a warning as shown below:
![Warning: Each child in a list should have a unique "key" prop.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4czsxb2nr587o6ozmw2e.png)

React is warning us that each item in the list should have a unique key.

Let's understand why keys are important: Say, for example, one of the items in the list changes, then having keys help React in identifying which item has changed in order to re-render the list.
You can read more about keys [here](https://reactjs.org/docs/lists-and-keys.html).

```jsx
const toppings = [
  "Golden Corn",
  "Paneer",
  "Tomato",
  "Mushroom",
  "Onion",
  "Black Olives",
]
function App() {
  return (
    <div className="app">
      <h2>Pizza Toppings</h2>
      <ul>
        {toppings.map(topping => {
          return <li key={topping}>{topping}</li>
        })}
      </ul>
    </div>
  )
}

export default App
```

Since the name of the topping is unique, we have used it as the key.

If there aren't any unique fields you may use the index of the array as well, as shown below:

```jsx
toppings.map((topping, index) => {
  return <li key={index}>{topping}</li>
})
```

# Implicit returns

Since we are using an arrow function as a callback function, we can write implicit returns since there is only a single line of code inside the callback.

```jsx
const toppings = [
  "Golden Corn",
  "Paneer",
  "Tomato",
  "Mushroom",
  "Onion",
  "Black Olives",
]
function App() {
  return (
    <div className="app">
      <h2>Pizza Toppings</h2>
      <ul>
        {toppings.map(topping => (
          <li>{topping}</li>
        ))}
      </ul>
    </div>
  )
}

export default App
```

# Separating the Logic and the JSX

If you are one of those persons who doesn't like to mix logic and JSX (surprisingly, I am not one of them! I like to mix logic and JSC no matter how clumsy it gets), you could have a separate function to have an array populated with the list of JSX as shown below.

```jsx
const toppings = [
  "Golden Corn",
  "Paneer",
  "Tomato",
  "Mushroom",
  "Onion",
  "Black Olives",
]

let listToRender = []

const generateList = () => {
  for (let index = 0; index < toppings.length; index++) {
    const topping = toppings[index]
    listToRender.push(<li key={index}>{topping}</li>)
  }
}

generateList()

function App() {
  return (
    <div className="app">
      <h2>Pizza Toppings</h2>
      <ul>{listToRender}</ul>
    </div>
  )
}

export default App
```

# Source code

You can view the source code [here](https://github.com/collegewap/react-for-loop) and do let me know in the comment section below about your favorite style of looping in React.