Skip to content

Commit

Permalink
Add initial SSR support
Browse files Browse the repository at this point in the history
  • Loading branch information
arunoda committed Feb 18, 2016
1 parent fcb4819 commit 5ff709e
Showing 1 changed file with 38 additions and 8 deletions.
46 changes: 38 additions & 8 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
/* global document*/
/* global document, Package*/

import domready from 'domready';
import ReactDOM from 'react-dom';
import React from 'react';

let ReactDOMServer = null;
let ReactDOM = null;
if (typeof window !== 'undefined') {
// now we are in the server
ReactDOM = require('react-dom');
} else {
ReactDOMServer = require('react-dom/server');
}

export let _isDomReady = false;
export function _ready(cb) {
if (_isDomReady) {
return cb();
}

const domready = require('domready');
domready(() => {
_isDomReady = true;
setTimeout(cb, 10);
Expand Down Expand Up @@ -52,12 +60,34 @@ export function _getRootNode(rootId, rootProps) {
}

export function mount(layoutClass, regions, options = {}) {
_ready(() => {
const {
rootId = 'react-root',
rootProps = {}
} = options;
options.rootId = options.rootId || 'react-root';
options.rootProps = options.rootProps || {};

if (ReactDOM) {
mountClient(layoutClass, regions, options);
} else {
mountServer(layoutClass, regions, options);
}
}

export function mountServer(layoutClass, regions, options) {
const el = React.createElement(layoutClass, regions);
const elHtml = ReactDOMServer.renderToString(el);

const {rootId, rootProps} = options;
var rootNodeHtml = _buildRootNode(rootId, rootProps);
var html = rootNodeHtml.replace('</div>', elHtml + '</div>');

if (Package['kadira:flow-router-ssr']) {
var FlowRouter = Package['kadira:flow-router-ssr'].FlowRouter;
var ssrContext = FlowRouter.ssrContext.get();
ssrContext.setHtml(html);
}
}

export function mountClient(layoutClass, regions, options) {
_ready(() => {
const {rootId, rootProps} = options;
const rootNode = _getRootNode(rootId, rootProps);
const el = React.createElement(layoutClass, regions);
ReactDOM.render(el, rootNode);
Expand Down

0 comments on commit 5ff709e

Please sign in to comment.