Brian Stanley Brian Stanley - 3 months ago 7
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: ->
div
className: 'CategoryProduct'
div
className: 'header'
@props.header
div
className: 'picture'
@props.src
div
className: 'description'
@props.description


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

@CategoryBox = React.createClass
render: ->
div
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

Answer

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: ->
    div
      className: 'CategoryBox'
      for prod in @props.productos
       React.createElement CategoryProduct, prod