How to learn react logo

These tutorials will give you a deeper understanding of React.js. Learn with examples from the Javascript UI library, covering the basics and the advanced.

Browse by tag:

Iterating over a list of data and generating an array of React Components

State

Lets look at the data we want to represent as DOM elements. We’ll render out a list of Favorite Bands.

const BandsData = [
  { bandName: "Modest Mouse" },
  { bandName: "Led Zeppelin" },
  { bandName: "The Beatles" },
  { bandName: "Guster" },
  { bandName: "Kygo" },
  { bandName: "Dear and the Headlights" },
  { bandName: "Grizzly Bear" }
];

We’ll give this new list to React and let it do it’s magic! This is all done with .map. Lets see the logic of this first before we apply it to a React Component. This should return us an array of JSX elements which are divs with the child of band.bandName interpolated as strings.

const newListOfData = BandsData.map(band => {
  return <div>{band.bandName}</div>;
});

Now lets apply this to a React Component.

const App = () => {
  return (
    <div className="App">
      {BandsData.map(band => {
        return <div>{band.bandName}</div>;
      })}
    </div>
  );
};

To make this work, there a few more steps:

  1. Take the list and set in on state
  2. Check your state by console.logging
  3. Map over bands and return all wrapped in divs with band.bandName and band.albumName
  4. Give each child a unique key prop
import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const BandsData = [
  { id: 0, bandName: "Led Zeppelin", albumName: "Led Zeppelin II" },
  { id: 1, bandName: "The Beatles", albumName: "Sgt. Peppers Lonely Heart Clubs Band" },
  { id: 2, bandName: "Grizzly Bear", albumName: "Veckatimist" }
];

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      name: "music",
      // Step 1
      bands: BandsData
    };
  }
  render() {
      // Step 2
    console.log(this.state);
    return (
      <div className="App">
        <h1>My favourite {this.state.name}</h1>
        // Step 3
        {this.state.bands.map(band => {
                // Step 4
          return <div key={band.id}>{band.bandName}: {band.albumName} </div>
        })}
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

How To Learn React is designed and developed by me, Blake Fletcher. It is a project intended to share the things I learn while working with the UI library. As I build things, complete tutorials, read blog posts, and watch videos, I'll add to the site. I hope to eventually bring on other contributors. If interested, send me an email at blkfltchr@gmail.com.