ref is a class component only feature in Reactjs, we have learned how to access DOM object using ref and current.
Steps
Following steps are required to use the callback ref
- Create callback property and assign to null
- Create set method for assign a DOM element to the property
- Attach element to input
The callback property
First we need to create a property for callback ref as follows
this.callBackRef=null
this.setCbRef= element =>{
this.callBackRef=element
}
We have created a callBackRef property and using the setCbRef can set DOM element to the property.
Attach the element to input
Using the input’s ref props we can attach the callbackref property using the setter function as follows
<input type="text" ref={this.setCbRef} />
One of the advantage of using this method is that we can directly access the DOM element using callbackref property instead of using current which we have seen in the first method of using ref.
Here is the complete component code for the project
import React, { Component } from 'react'
class InputRef extends Component {
constructor(props) {
super(props)
this.callBackRef=null
this.setCbRef= element =>{
this.callBackRef=element
}
}
componentDidMount(){
if(this.callBackRef)
{
this.callBackRef.focus()
}
}
clickHandler=()=>{
alert(this.callBackRef.value)
}
render() {
return (
<div>
<input type="text" ref={this.setCbRef} />
<button onClick={this.clickHandler}>Click me </button>
</div>
)
}
}
export default InputRef