The basic structure of a React+Flux application (see other examples)
- /src/actions/AppActions.js - Action creators (Flux)
- /src/components/Application.js - The top-level React component
- /src/constants/ActionTypes.js - Action types (Flux)
- /src/core/Dispatcher.js - Dispatcher (Flux)
- /src/stores/AppStore.js - The primary store (Flux)
- /src/stores/Store.js - Base class for stores (Flux)
- /src/app.js - Client-side startup script
- /src/server.js - Server-side startup script
// src/components/Application.js
var React = require('react');
var Application = React.createClass({
propTypes: {
path: React.PropTypes.string.isRequired,
onSetTitle: React.PropTypes.func.isRequired
},
render() {
var page = AppStore.getPage(this.props.path);
this.props.onSetTitle(page.title);
return (
<div className="container">
<h1>{page.title}</h1>
<div>{page.content}</div>
</div>
);
}
});
module.exports = Application;// src/app.js
var React = require('react');
var Dispatcher = require('./core/Dispatcher');
Dispatcher.register((payload) => {
var action = payload.action;
if (action.actionType === ActionTypes.CHANGE_LOCATION) {
history.pushState({}, document.title, action.path);
app.setProps({path: action.path});
}
});
var path = window.location.pathname + window.location.search + window.location.hash;
var app = React.createElement(require('./components/Application'), {
path: path,
onSetTitle: (title) => document.title = title
}));
app = React.render(app, document.body);var React = require('react');
var express = require('express');
var _ = require('lodash');
// The top-level React component + HTML template for it
var Application = React.createFactory(require('./components/layout/Application'));
var template = fs.readFileSync(path.join(__dirname, 'index.html'), {encoding: 'utf8'});
var server = express();
server.set('port', (process.env.PORT || 5000));
// Server-side rendering (SSR)
server.get('*', function(req, res) {
var data = {};
var component = Application({
path: req.url,
onSetTitle: (title) => data.title = title,
onPageNotFound: () => res.status(404)
});
data.body = React.renderToString(component);
var html = _.template(template, data);
res.send(html);
});
server.listen(server.get('port'), function() {
console.log('Node app is running at http://localhost:' + server.get('port'));
});