Skip to content

Commit 13fa96a

Browse files
authored
Improve bad ref invariant (facebook#13408)
1 parent b2adcfb commit 13fa96a

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

packages/react-dom/src/__tests__/refs-test.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,45 @@ describe('ref swapping', () => {
301301
const a = ReactTestUtils.renderIntoDocument(<A />);
302302
expect(a.refs[1].nodeName).toBe('DIV');
303303
});
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+
});
304343
});
305344

306345
describe('root level refs', () => {

packages/react-reconciler/src/ReactChildFiber.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ function coerceRef(
175175
} else {
176176
invariant(
177177
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.',
179179
);
180180
invariant(
181181
element._owner,

0 commit comments

Comments
 (0)