Accessing the DOM in Reactjs


Ref is a feature in Reactjs, which allow us to directly access the DOM object. To make this clear first create simple input component.

 class InputRef extends Component {
    constructor(props) {
        super(props)
       
    }
   render() {
       return (
           <div>
               <input type="text"  } />
           </div>
      )
  }
}

Following steps are required to use the ref in your class

  • Create ref in the constructor
  • Refer the ref in input

Create ref

We can create ref using the React.createRef() method as follows

 this.input_ref=React.createRef()

Make a reference

We can access the DOM using the ref object and assign it to the input tags ref props.

 <input type="text" ref={this.input_ref} />

componentDidMount()

This is a Lifecyle method of the component which occurs once when the component loaded or page refreshed. In this method we can use the focus method to focus the text input as follow

  componentDidMount(){
    this.input_ref.current.focus()
    }

Ref make to possible to access the current state of the object we referring by using current object.

Here is the complete code for the component


class InputRef extends Component {
    constructor(props) {
        super(props)
        this.input_ref=React.createRef()
    }

    componentDidMount(){
     this.input_ref.current.focus()
    }
   render() {
       return (
           <div>
               <input type="text" ref={this.input_ref} />
           </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.