Author -  Sai gowtham

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.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY