What is the different between the ref={callback} and the ref = "myInput" in react?
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
Update
Per Facebook Docs using strings for refs is consider legacy and they "recommend using either the callback pattern or the createRef API instead."
When you assign a ref={callback}
like <input type="text" ref={(input) => {this.textInput = input}}/>
what basically you are doing is saving the ref with the name textInput
for future use. So instead of using ref="myInput"
and then using this.refs.myInput
we can use the call back bethod and then access the component later like this.textInput
.
Here is a demo for the same, whereby we are accessing the input value
using ref
on button click
class App extends React.Component {
constructor(){
super();
}
handleClick = () => {
console.log(this.textInput.value);
}
render() {
return (
<div>
<input type="text" ref={(input) => {this.textInput = input}}/>
<button type="button" onClick={this.handleClick}>Click</button>
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.4/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.4/react-dom.min.js"></script>
<div id="app"></div>