Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add warning for ref to a stateless component #4943

Merged
merged 5 commits into from
Oct 6, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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