@samitouri / QOS-React-2 / commits / 7df127db31

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.

Pete Hunt committed Nov 18, 2013 at 10:40 UTC 7df127db31c7429cf461138b9e82c82eb78cec17
2 files changed +40 -2
src/environment/ReactServerRendering.js
+16 -2
@@ -18,17 +18,31 @@
18 */
19 "use strict";
20
21 +var ReactComponent = require('ReactComponent');
22 +var ReactInstanceHandles = require('ReactInstanceHandles');
23 var ReactMarkupChecksum = require('ReactMarkupChecksum');
24 var ReactReconcileTransaction = require('ReactReconcileTransaction');
23 -var ReactInstanceHandles = require('ReactInstanceHandles');
25 +
26 +var invariant = require('invariant');
27
28 /**
26 - * @param {object} component
29 + * @param {ReactComponent} component
30 * @param {function} callback
31 */
32 function renderComponentToString(component, callback) {
33 // We use a callback API to keep the API async in case in the future we ever
34 // 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 +
46 var id = ReactInstanceHandles.createReactRootID();
47 var transaction = ReactReconcileTransaction.getPooled();
48 transaction.reinitializeTransaction();
src/environment/__tests__/ReactServerRendering-test.js
+24
@@ -228,4 +228,28 @@ describe('ReactServerRendering', function() {
228 ReactTestUtils.Simulate.click(instance.refs.span.getDOMNode());
229 expect(numClicks).toEqual(1);
230 });
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 + });
255 });