Conditional loading of components
# posts/show.html.erb | |
<%= react_component("ShowPost", render(template: 'posts/show.json.jbuilder')) %> | |
# posts/show.json.jbuilder | |
json.post do | |
json.extract!(@post, :id, :user_id, :title, :body) | |
end | |
json.comments(@comments) do |comment| | |
json.extract!(comment, :id, :user_id, :body) | |
end if @comments | |
json.users(@users) do |user| | |
json.extract!(user, :id, :name) | |
end if @users | |
# controllers/posts_controller.rb | |
def show | |
@post = Post.find(params[:id]) | |
if some condition | |
@comments = @post.comments.includes(:user) | |
@users = @comment.flat_map(&:user).uniq | |
end | |
end | |
// components/show_post.js.jsx | |
var ShowPost = React.createClass({ | |
propTypes: { | |
post: React.PropTypes.object.isRequired, | |
comments: React.PropTypes.array, | |
users: React.PropTypes.array | |
}, | |
render: function() { | |
var comments = null; | |
if (this.props.comments !== undefined) { | |
comments = ( | |
<div> | |
<h2>Comments</h2> | |
<CommentsList comments={this.props.comments} usres={this.props.users} /> | |
</div> | |
); | |
} | |
return ( | |
<div> | |
<h1>{this.props.post.title}</h1> | |
<Post post={this.props.post} /> | |
{comments} | |
</div> | |
); | |
} | |
}); |
This comment has been minimized.
This comment has been minimized.
Ok, now a Flux version (of the JS only). Yes, there's a lot more files here. But if you're using these stores over multiple components, the initial overhead pays out completely over time. You can also define helpers to make the coding DRYer (we have a
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Here's an example of the same thing with asynchronous data loading. This is not a Flux example, it's a proof-of-concept to show what it's like if the parent component fetches its own data.
You'll also note I renamed the parent to ShowPostController. On our team, any component that fetches data, watches for data changes, and keeps it all in state, is called a Controller. Their only job is to compose stateless components and pass data into them as props.