Reputation: 2978
I'm building a very simple blog app with React on the front-end and Rails on the backend. I can't quite figure out how to handle this error:
Uncaught Error: Posts.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
I have two react components, Post and Posts. Both are extremely simple. Here is Posts:
var Posts = React.createClass({
getInitialState: function(){
return {
posts: this.props.posts
}
},
render: function(){
var that = this;
var postBoard = this.state.posts.map(function(post){
return (
<Post post={post} key={post.id} />
);
});
return (
{ postBoard }
);
}
});
Here is Post:
var Post = React.createClass({
getInitialState: function(){
return {
post: this.props.post
}
},
render: function(){
return (
<div class="col-md-12">
<h3>{this.state.post.title}</h3>
<p>{this.state.post.content}</p>
</div>
);
}
});
Here is the Rails index view for Posts. I am using the react-rails gem:
<div class="container-fluid">
<div class="row">
<div class="col-md-6 col-md-push-3">
<h1>Posts</h1>
<%= react_component( "Posts", { posts: @posts }) %>
<br>
<%= link_to 'New Post', new_post_path %>
</div>
</div>
</div>
Here is the index action in my Posts controller:
def index
@posts = Post.all
end
I can't figure out what is causing this. It's been a few weeks since I've used React. I am clearly rusty. Help!
Upvotes: 0
Views: 102
Reputation: 12093
Wrap postBoard
inside div. The reason of error is return methods return only one element. In your case postBoard
is array. If the length of postBoard
array is equal to 1, it should work without wraping it inside div
element
return (
<div>
{ postBoard }
</div>
);
Upvotes: 1