0

I am doing React + Rails application, for JSON I use default jbuilder. But as react-rails official documentation suggests I add a root node to the JSON like that:

{
  "comments":
      [
        {"id":1,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/1.json"}
      ]
}

in my Javascript file I want to do something like this:

var commentNodes = this.props.comments.map(function(comment,index){
   return (
     <Comment author_name={comment.author_name} comment_text={comment.comment_text} key={index} />
    );
});

but since now I have root node, I can not use this.props.comment.map I get an error:

Uncaught TypeError: this.props.comments.map is not a function

EDIT: I add comments to component as follows:

<CommentList comments={this.state.comments}/>
knowbody
  • 8,106
  • 6
  • 45
  • 70
yerassyl
  • 2,958
  • 6
  • 42
  • 68
  • Could you add how do you pass arguments to component ? – Oleksandr T. Jun 30 '15 at 05:08
  • You can not do map on a JavaScript object (JSON). There is no native implementations. Check [this](http://stackoverflow.com/questions/14810506/map-for-objects-instead-of-arrays) for explanation. To me it looks like you are passing the whole JSON object, when you want to pass the list within the "comments". – magnudae Jun 30 '15 at 08:05

1 Answers1

1

Try this:

const jsonObj = {
    "comments": [
        { "id":1, "author_name":null, "comment_text":null, "url":"http://localhost:3000/comments/1.json"} 
    ]
}

this.setState({
    comments: jsonObj.comments
})

<CommentList comments={this.state.comments} />

// in render() of CommentList
return (
    <div>
        {this.props.comments.map(this._createComment)}
    </div>
); 

_createComment({author_name, comment_text, id}) {
    return (
        <Comment 
            author_name={author_name} 
            comment_text={comment_text} 
            key={id} />
    );
}

Here is a simple DEMO of how to use .map

marcel
  • 2,967
  • 1
  • 16
  • 25