React: [Docs] [Question] Refs - Callback vs String

Created on 11 Mar 2016  ·  3Comments  ·  Source: facebook/react

I was reading the docs again, it's not clear to me the difference between defining a ref as a callback vs string:

<input ref={input => this._input = input} /> vs <input ref="input" />

Can someone clarify to me please?

Most helpful comment

If you define ref as a string, it will be available on this.refs object, for example, this.refs.input.
If you define a callback ref, you are free to do anything with it, including saving it on this if you’d like.

The string refs are eventually going to be deprecated. Callback refs were introduced later but they cover all use cases of string refs and don’t have some of their downsides. I suggest you to always use callback refs in the new code you write.

In the future, please consider asking questions on StackOverflow. We don’t officially consider issue tracker to be a support forum, and unfortunately GitHub search does not work as well as StackOverflow search, so it’s likely somebody is going to ask this again. Whereas if you posted this on StackOverflow, it’s likely you’d get a good answer, your question would get voted up, and more people would have learned from it and found it in the future.

All 3 comments

If you define ref as a string, it will be available on this.refs object, for example, this.refs.input.
If you define a callback ref, you are free to do anything with it, including saving it on this if you’d like.

The string refs are eventually going to be deprecated. Callback refs were introduced later but they cover all use cases of string refs and don’t have some of their downsides. I suggest you to always use callback refs in the new code you write.

In the future, please consider asking questions on StackOverflow. We don’t officially consider issue tracker to be a support forum, and unfortunately GitHub search does not work as well as StackOverflow search, so it’s likely somebody is going to ask this again. Whereas if you posted this on StackOverflow, it’s likely you’d get a good answer, your question would get voted up, and more people would have learned from it and found it in the future.

Thank you again @gaearon. I'll use StackOverflow next time.

No problem! Please feel free to submit a pull request to the documentation if you feel like we could make it more obvious that we recommend the callback ref pattern in the new code.

Was this page helpful?
0 / 5 - 0 ratings