Using callbackref for accessing DOM object in Reactjs


ref is a class component only feature in Reactjs, we have learned how to access DOM object using ref and current.

Accessing the DOM in Reactjs - How to access DOM directly in Reactjs

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

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.