Skip to content

Commit 7df127d

Browse files
petehuntzpao
authored andcommitted
Better error message for renderComponentToString()
Reported on Twitter by AirBnb (who are integrating React into their open-source JS framework). They made a mistake and passed a string in as the component. We should have a better error message for that.
1 parent 8529f1b commit 7df127d

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

src/environment/ReactServerRendering.js

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,31 @@
1818
*/
1919
"use strict";
2020

21+
var ReactComponent = require('ReactComponent');
22+
var ReactInstanceHandles = require('ReactInstanceHandles');
2123
var ReactMarkupChecksum = require('ReactMarkupChecksum');
2224
var ReactReconcileTransaction = require('ReactReconcileTransaction');
23-
var ReactInstanceHandles = require('ReactInstanceHandles');
25+
26+
var invariant = require('invariant');
2427

2528
/**
26-
* @param {object} component
29+
* @param {ReactComponent} component
2730
* @param {function} callback
2831
*/
2932
function renderComponentToString(component, callback) {
3033
// We use a callback API to keep the API async in case in the future we ever
3134
// need it, but in reality this is a synchronous operation.
35+
36+
invariant(
37+
ReactComponent.isValidComponent(component),
38+
'renderComponentToString(): You must pass a valid ReactComponent.'
39+
);
40+
41+
invariant(
42+
typeof callback === 'function',
43+
'renderComponentToString(): You must pass a function as a callback.'
44+
);
45+
3246
var id = ReactInstanceHandles.createReactRootID();
3347
var transaction = ReactReconcileTransaction.getPooled();
3448
transaction.reinitializeTransaction();

src/environment/__tests__/ReactServerRendering-test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,4 +228,28 @@ describe('ReactServerRendering', function() {
228228
ReactTestUtils.Simulate.click(instance.refs.span.getDOMNode());
229229
expect(numClicks).toEqual(1);
230230
});
231+
232+
it('should throw with silly args', function() {
233+
expect(
234+
ReactServerRendering.renderComponentToString.bind(
235+
ReactServerRendering,
236+
'not a component',
237+
function() {}
238+
)
239+
).toThrow(
240+
'Invariant Violation: renderComponentToString(): You must pass ' +
241+
'a valid ReactComponent.'
242+
);
243+
244+
expect(
245+
ReactServerRendering.renderComponentToString.bind(
246+
ReactServerRendering,
247+
React.DOM.div(),
248+
'not a function'
249+
)
250+
).toThrow(
251+
'Invariant Violation: renderComponentToString(): You must pass ' +
252+
'a function as a callback.'
253+
);
254+
});
231255
});

0 commit comments

Comments
 (0)