Skip to content

Commit

Permalink
Warn if a function is passed to ref on an SFC
Browse files Browse the repository at this point in the history
  • Loading branch information
Brandon Dail authored and Brandon Dail committed Nov 20, 2016
1 parent 2854eb9 commit b6aaa92
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
8 changes: 7 additions & 1 deletion src/renderers/shared/stack/reconciler/ReactRef.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
'use strict';

var ReactOwner = require('ReactOwner');
var warning = require('warning');

import type { ReactInstance } from 'ReactInstanceType';
import type { ReactElement } from 'ReactElementType';
Expand All @@ -21,7 +22,12 @@ var ReactRef = {};

function attachRef(ref, component, owner) {
if (typeof ref === 'function') {
ref(component.getPublicInstance());
var instance = component.getPublicInstance();
warning(
instance !== null,
'Stateless function components cannot have refs.'
);
ref(instance);
} else {
// Legacy ref
ReactOwner.addComponentAsRefTo(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,9 @@ describe('ReactStatelessComponent', () => {
it('should warn for functional refs in pure functions', function() {
spyOn(console, 'error');
function Child() {
return <div ref={node => {}} />;
return <div/>;
}
ReactTestUtils.renderIntoDocument(<Child test="test" />);
ReactTestUtils.renderIntoDocument(<Child ref={node => {}} />);
expect(console.error.calls.count()).toBe(1);
expect(console.error.calls.argsFor(0)[0]).toContain(
'Stateless function components cannot have refs.'
Expand Down

0 comments on commit b6aaa92

Please sign in to comment.