jkj2000
jkj2000

Reputation: 1593

Why can't I map() over this array in JSX?

I must be doing something wrong. I'm working on a codepen that makes a call to a REST endpoint for beer information, then I loop over it and display some of the info. Nothing fancy and it's not complete yet in terms of nice looking CSS etc. but the looping over my array of beers doesn't work:

https://codepen.io/larryq/pen/yKyMOz

The key section is this bit below. I get my data back from the endpoint and add it to a 'beersList' array that's in my state. Then in the JSX I loop over it:

       this.state.beerList.map(beer => {
          <div>
            <div className="beer-img">
              <img src={beer.img} height="350" />
            </div>
            <div className="beer-info">
              <h2>{beer.name}</h2>
            </div>
          </div>
        })

..the trouble is, nothing appears on the screen, none of the <div>s are generated.

I know for a fact when debugging that beerList is populated with the data I'm after, and in the console I can map over it and print out the information. But on the screen here nothing happens and I can't figure out why?

Upvotes: 0

Views: 138

Answers (2)

Fabian Schultz
Fabian Schultz

Reputation: 18546

You have to return the JSX inside map:

this.state.beerList.map(beer => {
  return (
    <div key={beer.id}>
      <div className="beer-img">
        <img src={beer.img} height="350" />
      </div>
      <div className="beer-info">
        <h2>{beer.name}</h2>
      </div>
    </div>
  );
});

You can also return the JSX directly using ():

this.state.beerList.map(beer => (
  <div key={beer.id}>
    <div className="beer-img">
      <img src={beer.img} height="350" />
    </div>
    <div className="beer-info">
      <h2>{beer.name}</h2>
    </div>
  </div>
));

Upvotes: 6

Aaqib
Aaqib

Reputation: 10350

As suggested by Fabian , Make use of () or return and make sure to give key property inside the .map() to avoid the Reactjs Warning like :

        {this.state.beerList.map(beer => (
          <div key={beer.id}>
            <div className="beer-img">
              <img src={beer.img} height="350" />
            </div>
            <div className="beer-info">
              <h2>{beer.name}</h2>
            </div>
          </div>
        ))}

Upvotes: 2

Related Questions