How to iterate over an array that's inside an object in React JS

Viewed 5079

Imagine I have an array of objects like so:

const chefs = [
  {
    key: 1,
    images: ['http://lorempixel.com/400/400/sports/', 'http://lorempixel.com/400/400/abstract/', 'http://lorempixel.com/400/400/animals/', 'http://lorempixel.com/400/400/city/', 'http://lorempixel.com/400/400/people/']
  }
]

And I'm wanting to assign each of the images inside of the images array to a React component called CarrouselItem using props:

class CarrouselItem extends React.Component {
  render() {

    return (
      <div>
        <img src={this.props.imageUrl} />
      </div>
    )
  }
}

Which is then placed into a parent component called Carrousel, where I loop over the object and return the images inside, to be placed inside of the CarrouselItem component:

class Carrousel extends React.Component {
  render() {
    return (
      <div>
        <h4>Slide image</h4>
        {chefs.map((chef, index) => {
          return <CarrouselItem imageUrl={chef.images[index]} />
        })}
      </div>
    )
  }
}

What I expect to happen

The map function should iterate over all of the objects (in this case, just one of them) which then creates X number of CarrouselItem components, each with an <img> that's taken from the images array.

What actually happens

Unfortunately I'm only getting the first item in the array (in this case, 'http://lorempixel.com/400/400/sports/').

Could someone be so kind to explain where I'm going wrong here?

Link to CodePen.

3 Answers
Related