Long Phan Long Phan - 2 months ago 6
React JSX Question

I am trying to map over an array and find the index of object within array

I have a component and I would like to find the index within the array of objects(for now I have a hardcoded array of objects, but later would be using a call to fetch data). I want to add a mdOffset of 2 on every fifth position of the array. How would i go about doing this? My code:

export default class Winks extends Component {
constructor () {
super()
this.state ={
items: [
{ id:1, name: "The Kooples - white top", url:"bloomingdales.com", src: "assets/male.png" },
{ id:2, name: "Sandro-Orange Zipper", url:"saksfifth.com", src: "assets/female.png" },
{ id:3, name: "Sandro-Orange Zipper", url:"saksfifth.com", src: "assets/female.png" },
{ id:4, name: "Sandro-Orange Zipper", url:"saksfifth.com", src: "assets/female.png" },
{ id:1, name: "Sandro-Orange Zipper", url:"saksfifth.com", src: "assets/female.png" },
{ id:1, name: "The Kooples - dress", url:"bloomingdales.com", src: "assets/male.png" },
{ id:1, name: "The Kooples - dress", url:"bloomingdales.com", src: "assets/male.png" },
]
}
}

render () {

var listItems = this.state.items.map.bind(this)(function(item) {
if (this.state.items.indexOf(item) % 5 === 0 ) {
var columns = (
<Col md={2} mdOffset={2}>
<img className='img-responsive' src={item.src}></img>
<Row>
<span>{item.name}</span>
</Row>
<Row className="pull-right">
<i className="fa fa-heart"></i>
</Row>
</Col>
)
}

else {
var columns = (
<Col md={2}>
<img className='img-responsive' src={item.src}></img>
<Row>
<span>{item.name}</span>
</Row>
<Row className="pull-right">
<i className="fa fa-heart"></i>
</Row>
</Col>
)
}

return columns
});

return (
<Row>
{listItems}
</Row>
)
}
}

Answer

When you map you get the index of the element as second argument https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Ex:

arr.map(function(item, index) {
  if (index % 5 === 0) {
    // do your stuff here
  }
});

Or

arr.map(function(item, index) {
  <Col mdOffset={index % 5 === 0 ? 2 : null}>

  </Col>
});