Open In App

What is the equivalent of document.getElementById() in React?

Last Updated : 01 Feb, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In React we have a concept of Refs which is equivalent to document.getElementById() in Javascript. Refs provide a way to access DOM nodes or React elements created in the render method.

Creating Refs

Refs are created using React.createRef() and attached to React elements via the ref attribute. 

class App extends React.Component {
 constructor(props) {
   super(props);
   //creating ref
   this.myRef= React.createRef();
 }
 render() {
 //assigning ref
   return <div ref={this.myRef} />;
 }
}

Accessing Refs

When we assign a ref to an element in the render, then we can access the element using the current attribute of the ref.

const node = this.myRef.current;

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

filepathe- src/App.js:

Javascript




import React from 'react'
  
class App extends React.Component {
  
    constructor(props) {
        super(props);
        this.myRef = React.createRef();
      }
    onFocus() {
      this.myRef.current.value ="focus"
    }
    
    onBlur() {
      this.myRef.current.value = "blur"
    }
    
    render() {
      return (
        <div>
          <input
            ref= {this.myRef}
            onFocus={this.onFocus.bind(this)}
            onBlur={this.onBlur.bind(this)}
          />
        </div>
      );
    }
  }
  
  export default App;


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads