top of page
Logo der Online Agentur mdwp

Loop

In React JS, Loop refers to the process of iterating over and rendering an array of elements. Looping allows you to manipulate or display data in a repetitive fashion, which is useful for creating dynamic user interfaces or working with large sets of data.

In React, you typically perform loops using the JavaScript array functions .map(), .filter(), and .reduce(). Of these, .map() is most commonly used to loop through arrays and generate a list of React elements. Each time the function runs, it returns a new React element, which is placed in the output array.

Here is an example of how one might use .map() to create a loop in a React component:

```jsx
import React from 'react';

class List extends React.Component {
constructor(props) {
super(props);
this.state = { items: ['Apple', 'Banana', 'Cherry'] };
}

render() {
return (
<ul>
{this.state.items.map((item, index) =>
<li key={index}>{item}</li>
)}
</ul>
);
}
}

export default List;
```

In this example, the map function is used to loop through the 'items' array in the state, and for each item, it returns a 'li' tag containing the item. The 'key' prop is a special string attribute that helps React identify which items have changed, are added, or are removed. Most often, we use IDs from our data as keys. Here we are using the index as a key.
But it’s better to use unique string values as it makes your code more robust and prevents bugs if list order changes or items are added/removed from list.

bottom of page