Reactjs – the different between the ref={callback} and the ref = “theInput” in react

reactjs

as the link https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute

It then only gives an example of using the component immediately. I'm trying to find out how i would use this function to access the component immediately, and save the component for future use, as it says we are able to do.

Best Answer

The difference is using ref={callback} react passes the responsibility of managing the reference storage back to you. When you use ref="sometext", under the covers react has to create a refs property on your class and then add all the ref="sometext" statements to it.

While its nice to have a simple this.refs.sometext access to components its difficult and error prone on the react side to clean up this refs property when the component is destroyed. It's much easier for react to pass you the component and let you handle storing it or not.

According to the react docs

React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts.

This is actually a pretty slick idea, by passing null on unmount and calling your callback again you automatically clean up references.

To actually use it all you have to do is access it from any function like so:

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
  }

  focus() {
    // Explicitly focus the text input using the raw DOM API
    this.textInput.focus();
  }

  render() {
    // Use the `ref` callback to store a reference to the text input DOM
    // element in this.textInput.
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focus}
        />
      </div>
    );
  }
}

The callback you set on ref will receive the component as the first parameter, the 'this' word will be the current class 'CustomTextInput' in this example. Setting this.textInput in your callback will make textInput available to all other functions like focus()

Concrete Example

Tweet from Dan Abermov showing a case where ref callbacks work better

enter image description here

Update

Per Facebook Docs using strings for refs is consider legacy and they "recommend using either the callback pattern or the createRef API instead."