Dave Lunny
Dave Lunny

Reputation: 770

Pass an array through a React component

Trying to keep it simple here.

I have some data. It contains a list of objects we'll call items. I loop through the items, and pass various properties to a component like so:

  render: function(){
    var itemList = [];

    items.forEach(function(item){
      itemList.push(<Component name={item.name} tags={item.tags} />)
    })
    return(
      <ul id="item-list">
        {itemList}
      </ul>
    )
  }

So the issue here is that item.tags is an array. From within my component, I am just doing something simple like display the name and then loop through the tags to display them:

  render: function(){
    var tags = [];

    this.props.tags.forEach(function(tag){
      tags.push( <li>{tag}</li> />)
    })
    return(
      <li>
        <h1>{this.props.name}</h1>
        <ul>
          {tags}
        </ul>
      </li>
    )
  }

From within the component, tags is undefined.

What do I do/am I doing wrong, because I am very new to React. Thanks!

Upvotes: 1

Views: 5891

Answers (1)

Sean Adkinson
Sean Adkinson

Reputation: 8605

May need more code to be helpful.

If your Component class is being given a tags prop, this.props.tags will always be a reference to it.

Is there any chance you are doing something funny, such as cloneWithProps, or using a dynamic <Component/> class?

You might try passing in item as a prop, and pull out the tags in the component.

<Component item={item}/>

That will let you see easier why tags isn't available.

Upvotes: 3

Related Questions