diff --git a/src/renderers/shared/stack/reconciler/ReactRef.js b/src/renderers/shared/stack/reconciler/ReactRef.js index a7350cc6a8a73..e5a0928671fc5 100644 --- a/src/renderers/shared/stack/reconciler/ReactRef.js +++ b/src/renderers/shared/stack/reconciler/ReactRef.js @@ -13,6 +13,7 @@ 'use strict'; var ReactOwner = require('ReactOwner'); +var warning = require('warning'); import type { ReactInstance } from 'ReactInstanceType'; import type { ReactElement } from 'ReactElementType'; @@ -21,7 +22,18 @@ var ReactRef = {}; function attachRef(ref, component, owner) { if (typeof ref === 'function') { - ref(component.getPublicInstance()); + var instance = component.getPublicInstance(); + if (__DEV__) { + var componentName = component && component.getName ? + component.getName() : 'a component'; + warning(instance != null, + 'Stateless function components cannot be given refs ' + + '(See %s%s).', + componentName, + owner ? ' created by ' + owner.getName() : '' + ); + } + ref(instance); } else { // Legacy ref ReactOwner.addComponentAsRefTo( diff --git a/src/renderers/shared/stack/reconciler/__tests__/ReactStatelessComponent-test.js b/src/renderers/shared/stack/reconciler/__tests__/ReactStatelessComponent-test.js index 8577ca180e688..0c7a6e1278eae 100644 --- a/src/renderers/shared/stack/reconciler/__tests__/ReactStatelessComponent-test.js +++ b/src/renderers/shared/stack/reconciler/__tests__/ReactStatelessComponent-test.js @@ -146,7 +146,25 @@ describe('ReactStatelessComponent', () => { ); }); - it('should warn when given a ref', () => { + it('should warn for functional refs in pure functions', function() { + spyOn(console, 'error'); + + var Parent = React.createClass({ + displayName: 'Parent', + render: function() { + return {}}/>; + }, + }); + + ReactTestUtils.renderIntoDocument(); + expect(console.error.calls.count()).toBe(1); + expect(console.error.calls.argsFor(0)[0]).toContain( + 'Stateless function components cannot be given refs ' + + '(See StatelessComponent created by Parent).', + ); + }); + + it('should warn when given a ref', function() { spyOn(console, 'error'); class Parent extends React.Component {