Brian Stanley Brian Stanley - 2 months ago 5
CoffeeScript Question

How can I call a component inside a loop

I want to call a CategoryProduct component inside a forEach loop in the CategoryBox Component.

My input:

- productos = [ { header: 'car', src: 'picture.jpg', description: 'the car' } ]

CategoryProduct component:

@CategoryProduct = React.createClass
render: ->
className: 'CategoryProduct'
className: 'header'
className: 'picture'
className: 'description'

Then I try to call the CategoryProduct component in the CategoryBox component:

@CategoryBox = React.createClass
render: ->
className: 'CategoryBox'
@props.productos.forEach (prod) ->
React.createElement CategoryProduct, { header: prod.header, src: prod.src, description: prod.description }

But the output is nothing. I did a console log inside the loop and is getting in without problem but it doesn't go inside the CategoryProduct component


You should look into coffeescript's loops and comprehensions. They are much nicer than the JS ones and due coffeescripts implicit return, the loop will return an array containing the values on the last line inside the loop.

For example:

a = [1,2,3,4,5,6]
b = for item in a 
  z = item * 2
  z + 1

Then b would be [3, 5, 7, 9, 11, 13]

So your code would read:

@CategoryBox = React.createClass
  render: ->
      className: 'CategoryBox'
      for prod in @props.productos
       React.createElement CategoryProduct, prod