Improve bad ref invariant (#13408)
Dan Abramov committed
Aug 15, 2018 at 18:30 UTC
13fa96a54743780246efb9cba5a24b1d6838a2e4
2 files changed
+40
-1
packages/react-dom/src/__tests__/refs-test.js
+39
@@ -301,6 +301,45 @@ describe('ref swapping', () => {
301
const a = ReactTestUtils.renderIntoDocument(<A />);
302
expect(a.refs[1].nodeName).toBe('DIV');
303
});
304
+
305
+ it('provides an error for invalid refs', () => {
306
+ expect(() => {
307
+ ReactTestUtils.renderIntoDocument(<div ref={10} />);
308
+ }).toThrow(
309
+ 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.',
310
+ );
311
+ expect(() => {
312
+ ReactTestUtils.renderIntoDocument(<div ref={true} />);
313
+ }).toThrow(
314
+ 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.',
315
+ );
316
+ expect(() => {
317
+ ReactTestUtils.renderIntoDocument(<div ref={Symbol('foo')} />);
318
+ }).toThrow(
319
+ 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.',
320
+ );
321
+ // This works
322
+ ReactTestUtils.renderIntoDocument(<div ref={undefined} />);
323
+ ReactTestUtils.renderIntoDocument({
324
+ $$typeof: Symbol.for('react.element'),
325
+ type: 'div',
326
+ props: {},
327
+ key: null,
328
+ ref: null,
329
+ });
330
+ // But this doesn't
331
+ expect(() => {
332
+ ReactTestUtils.renderIntoDocument({
333
+ $$typeof: Symbol.for('react.element'),
334
+ type: 'div',
335
+ props: {},
336
+ key: null,
337
+ ref: undefined,
338
+ });
339
+ }).toThrow(
340
+ 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.',
341
+ );
342
+ });
343
});
344
345
describe('root level refs', () => {
packages/react-reconciler/src/ReactChildFiber.js
+1
-1
@@ -175,7 +175,7 @@ function coerceRef(
175
} else {
176
invariant(
177
typeof mixedRef === 'string',
178
- 'Expected ref to be a function or a string.',
178
+ 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.',
179
);
180
invariant(
181
element._owner,