react: ref callback argument is null
Do you want to request a feature or report a bug?
A bug 🐛
What is the current behavior?
The ref callback gets called with null as argument instead of an instance of the component. This only occurs when you write the component name starting with an uppercase character (PascalCase). If you write the component starting with a lowercase character (camelCase) everything works as expected.
This jsfiddle demonstrates how you get a null argument: https://jsfiddle.net/1v9vk4zb/
And this demonstrates how you get a correct reference: https://jsfiddle.net/a0d0owru/
As you can see I just renamed Button to lowercaseButton.
What is the expected behavior?
It should always pass the component instance as argument to the callback.
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
This occurs in v15.4.0 and v15.3.1. I didn’t tested any other versions.
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 6
- Comments: 16 (1 by maintainers)
The
lowerbaseButtonexample doesn’t use your component. Please read the relevant documentation. Your components should always start with an upper case letter if you use JSX.The
Buttonexample also works correctly. From the ref docs:So if you want to use refs, you need to define
Buttonas a class.The correct behaviour would be not passing
nullto functional components but rather throwing an error explaining what’s going on.We are printing a warning for this in master. It will be part of React 16.
We should warn about this by the way. You can track #7272 and #7267 for this.
No, why? Compute them in constructor when you initialize the state. If they depend on props, also recompute them in componentWillReceiveProps.