Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save rogaldh/11bfd420f51ab3c9f682 to your computer and use it in GitHub Desktop.

Select an option

Save rogaldh/11bfd420f51ab3c9f682 to your computer and use it in GitHub Desktop.

Project Files

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

The Top-level Component

// 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;

Client-side Startup Script (aka Bootstrap)

// 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) {
    window.history.pushState({}, document.title, action.path);
    application.setProps({path: action.path});
  }
});

var path = window.location.pathname + window.location.search + window.location.hash;
var application = React.createElement(require('./components/Application'), {
  path: path,
  onSetTitle: (title) => document.title = title
}));
application = React.render(application, document.body);

Server-side Startup Script

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);
});

Example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment