Last active
August 29, 2015 14:14
-
-
Save uberllama/a9e17127cdec1b08a2b4 to your computer and use it in GitHub Desktop.
Conditional loading of components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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> | |
); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
BaseStore
that all our stores extend from, and it takes care of all the repetitive events setup).