React for loop to render elements

React for loop to render elements

In this tutorial, we are going to learn about how to loop through array of elements in a react.

For loop

Consider we have an array of users, we need to loop them using for loop and render the elements into the dom.

We can do it like this in react.

import React from "react";

function App() {
  const users = ["user1", "user2", "user3"];
  const final = [];
  for (let  user of users) {
    final.push(<li key={user}>{user}</li>);  }
  return (
    <div className="App">
      <ul>{final}</ul>    </div>
  );
}

export default App;

In the above example, we defined a new array called final and on each iteration, we are pushing the each li element into the array and finally we are rendering it inside ul element.

In Class-based components, you can do it similarly.

example:

import React from "react";

class App extends React.Component {
  render() {
    const users = ["user1", "user2", "user3"];
    const final = [];
    for (let user of users) {
      final.push(<li key={user}>{user}</li>);
    }
    return (
      <div className="App">
        <ul>{final}</ul>
      </div>
    );
  }
}

export default App;

Map method

In the above example, we learned how to use for loop to render the array of elements now we can do it same thing by using JavaScript map method.

import React from "react";

class App extends React.Component {
  render() {
    const users = ["user1", "user2", "user3"];

    return (
      <div className="App">
        <ul>
        {users.map((user,index) =>            <li key={index}>{user}</li>        )}        </ul>
      </div>
    );
  }
}

export default App;

Note: If you don’t add a key prop to an element react warns you because react needs to track the element updates by using keys. key be should be unique value in your array.