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:
Map
over bands
and return all wrapped in divs
with band.bandName
and band.albumName
key
propimport 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);