react

How to use forEach loop in React


In this article, you are going to learn about how to use forEach loop in react.

In JavaScript, the forEach() loop is considered as an array method that is used to iterate each item of an array with the help of a callback function. Let me assume that you have already familiar with JavaScript fundamentals. Though we will demonstrate an example of forEach() loop in JavaScript before jumping into the react. See the below code example of JavaScript forEach() loop.

const myArray = [10, 20, 30, 40, 50]

myArray.forEach((el)=>{
    console.log(el)
})
/*
Output:
10
20
30
40
50
*/

Here, you can see that to implement the forEach() loop we do not have to follow any special rules. But Implementing this loop in a react application is a bit different. We need to iterate an array of data in our development journey and it is an essential part. JavaScript provides loops like for loop, for of loop, for in loop, foreach loop. We will explore the forEach() loop and how you can use it in react. To do so let’s see the below code example

import React from 'react'
import "./index.css"


function App() {

  const studentDetails = ['Alex', 'Anik', 'Deven', 'Rathore'];

  const names = []

  studentDetails.forEach((data) => {
    names.push(<h3 className='student_name'>{data}</h3>)
  })

  return (
    <div className='container'>
      {names}
    </div>
  )
}

export default App;

Here, we simply print the list of the student names with the help of the forEach loop. We also include our CSS file and give some styles so that the data can be visible in a nice way. Though this is not mandatory, you may design it in your own interest. Let’s see the output in the below section and check if our list of arrays iterates properly or not.

Here, you can see that our array items show properly in the output. This is how you can use forEach loop in React. There are different loops in JavaScript along with forEach loop and you may use them based on different use cases of your application.


Share on social media

//