Skip to content

Instantly share code, notes, and snippets.

@pedronauck
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedronauck/0952d93ea68ee70f924c to your computer and use it in GitHub Desktop.
Save pedronauck/0952d93ea68ee70f924c to your computer and use it in GitHub Desktop.
A simple structure example to use React with a router
/* file path: ./views/Posts */
'use strict';
var React = require('react');
var PostIndex = React.createClass({
render: function() {
var posts = this.props.posts.map(function(post, index) {
return (
<li key={post.id}>
<a href={'/post/' + post.id}>{post.title}</a>
</li>
);
});
return (
<div className='post-list'>
<h2>My Posts</h2>
<ul>
{posts}
</ul>
</div>
);
}
});
var PostShow = React.createClass({
render: function() {
var post = this.props.post;
return (
<div className='post-show'>
<h2>{post.title}</h2>
<p>
{post.content}
</p>
<a href='/posts'>Voltar</a>
</div>
);
}
});
module.exports = {
index: PostIndex,
show: PostShow
};
/* file path: ./routes/posts */
'use strict';
var request = require('superagent');
var React = require('react');
var PostsView = require('./views/Posts');
exports.loadPosts = function(ctx, next) {
var apiUrl = '/api/posts';
request.get(apiUrl, function(res) {
var posts = res.body.posts;
ctx.posts = posts;
next();
});
};
exports.loadPost = function(ctx, next) {
var postId = ctx.params.postId;
var apiUrl = '/api/posts/' + ctx.params.postId;
request.get(apiUrl, function(res) {
var post = res.body.post;
ctx.post = post;
next();
});
};
exports.index = function(ctx) {
React.renderComponent(
<PostsView.index posts={ctx.posts} />,
document.querySelector('#app')
);
};
exports.show = function(ctx) {
React.renderComponent(
<PostsView.show post={ctx.post} />,
document.querySelector('#app')
);
};
/* file path: ./routes */
'use strict';
var page = require('page');
var React = require('react');
var posts = require('./routes/posts');
page('/posts', posts.loadPosts, posts.index);
page('/posts/:postId', posts.loadPost, posts.show);
page();

Final structure:

.
routes.jsx
└─── routes
    |   posts.js
└─── views
    |   Posts.jsx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment