Skip to content

Commit

Permalink
[added] renderComponentToString()
Browse files Browse the repository at this point in the history
closes #36
  • Loading branch information
petehunt authored and ryanflorence committed Jun 20, 2014
1 parent d6b7e22 commit 31d1a6e
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
19 changes: 19 additions & 0 deletions modules/Router.js
Expand Up @@ -208,6 +208,25 @@ mergeProperties(Router.prototype, {
return component;
},

/**
* Renders this Router's component as a string. Since this may be an asynchronous
* process, this returns a Promise.
*/
renderComponentToString: function(path) {
invariant(
!this.state.props,
'You may only call renderComponentToString() on a new Router'
);

return this.dispatch(path).then(function() {
var route = this.route;
var state = this.state;
var descriptor = route.handler(state.props);
var markup = React.renderComponentToString(descriptor);
return markup;
}.bind(this));
},

handleRouteChange: function () {
this.dispatch(URLStore.getCurrentPath());
}
Expand Down
40 changes: 40 additions & 0 deletions specs/Router.spec.js
@@ -1,4 +1,5 @@
require('./helper');
var Promise = require('es6-promise').Promise;
var Router = require('../modules/Router');
var RouteComponent = require('../modules/components/Route');

Expand Down Expand Up @@ -125,6 +126,45 @@ describe('a Router with custom props', function() {
});
});

describe('a Router that renders on the server', function() {
it('works with async willTransitionTo()', function(done) {
var dataStore = 'goodbye';
var Layout = React.createClass({
render: function() {
return React.DOM.article(null, this.props.activeRoute);
}
});
var AsyncApp = React.createClass({
displayName: 'AsyncApp',
statics: {
willTransitionTo: function() {
return new Promise(function(resolve) {
setTimeout(function() {
dataStore = 'hello';
resolve();
}, 0);
});
}
},
render: function() {
return React.DOM.div(null, dataStore);
}
});

var router = Router(
RouteComponent({ path: '/', handler: Layout},
RouteComponent({ path: '/a', handler: AsyncApp }))
);

router.renderComponentToString('/a').then(function(result) {
expect(result.indexOf('div') > -1).toBe(true);
expect(result.indexOf('hello') > -1).toBe(true);

done();
});
});
});

function lastItem(array) {
return array[array.length - 1];
}

0 comments on commit 31d1a6e

Please sign in to comment.