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 3 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
4 changes: 3 additions & 1 deletion src/renderers/shared/reconciler/ReactCompositeComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -808,8 +808,10 @@ var ReactCompositeComponentMixin = {
attachRef: function(ref, component) {
var inst = this.getPublicInstance();
invariant(inst != null, 'Stateless function components cannot have refs.');
var publicComponentInstance = component.getPublicInstance();
warning(publicComponentInstance != null, 'Stateless function components cannot be given refs.');
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,22 @@ describe('ReactStatelessComponent', function() {
);
});

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

var Parent = React.createClass({
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.'
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now that this is a warning, I wonder if a more helpful message would be nice. Even if it was just Stateless function components cannot be given refs. Attempts to access this ref will fail.

Thoughts?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, would be good to give as much context as possible also.

Stateless function components cannot be given refs (see ChildComponentName created by OwnerComponentName). Attempts to access this ref will fail.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Donezo. Also added the ref name into the error: (See ref "stateless" in StatelessComponent created by Parent)

);
});

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