Skip to content

Commit

Permalink
Merge pull request #4943 from bspaulding/throw-stateless-ref
Browse files Browse the repository at this point in the history
Composite component throws on attaching ref to stateless component #4939
  • Loading branch information
sebmarkbage committed Oct 6, 2015
2 parents 6446a45 + c6a3eb1 commit 6d3a11e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/renderers/shared/reconciler/ReactCompositeComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -808,8 +808,21 @@ var ReactCompositeComponentMixin = {
attachRef: function(ref, component) {
var inst = this.getPublicInstance();
invariant(inst != null, 'Stateless function components cannot have refs.');
var publicComponentInstance = component.getPublicInstance();
if (__DEV__) {
var componentName = component && component.getName ?
component.getName() : 'a component';
warning(publicComponentInstance != null,
'Stateless function components cannot be given refs ' +
'(See ref "%s" in %s created by %s). ' +
'Attempts to access this ref will fail.',
ref,
componentName,
this.getName()
);
}
var refs = inst.refs === emptyObject ? (inst.refs = {}) : inst.refs;
refs[ref] = component.getPublicInstance();
refs[ref] = publicComponentInstance;
},

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,25 @@ describe('ReactStatelessComponent', function() {
);
});

it('should warn when given a ref', function() {
spyOn(console, 'error');

var Parent = React.createClass({
displayName: 'Parent',
render: function() {
return <StatelessComponent name="A" ref="stateless"/>;
},
});
ReactTestUtils.renderIntoDocument(<Parent/>);

expect(console.error.argsForCall.length).toBe(1);
expect(console.error.argsForCall[0][0]).toContain(
'Stateless function components cannot be given refs ' +
'(See ref "stateless" in StatelessComponent created by Parent). ' +
'Attempts to access this ref will fail.'
);
});

it('should provide a null ref', function() {
function Child() {
return <div />;
Expand Down

0 comments on commit 6d3a11e

Please sign in to comment.