DEV Community

Cover image for How to write for loops in React JSX
collegewap
collegewap

Posted on • Originally published at codingdeft.com

How to write for loops in React JSX

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:

npx create-react-app react-for-loop
Enter fullscreen mode Exit fullscreen mode

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

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

Using the map function

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

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
Enter fullscreen mode Exit fullscreen mode

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 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.

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.

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
Enter fullscreen mode Exit fullscreen mode

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:

toppings.map((topping, index) => {
  return <li key={index}>{topping}</li>
})
Enter fullscreen mode Exit fullscreen mode

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.

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
Enter fullscreen mode Exit fullscreen mode

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.

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
Enter fullscreen mode Exit fullscreen mode

Source code

You can view the source code here and do let me know in the comment section below about your favorite style of looping in React.

Discussion (0)