How to usedocument.getElementById() in ReactJS

In this approach, ele­ments are retrie­ved by their unique IDs using the­ document.getEleme­ntById() method. It is a standard DOM function that proves effe­ctive. 

Syntax:

const element = document.getElementById('yourElementId');

Example: Below is the code example of the above approach.

Javascript




import React, { Component } from 'react';
 
class App extends Component {
    handleClick = () => {
        const element = document.getElementById('myButton');
        if (element) {
         
            // Manipulate the retrieved element's style
            element.style.backgroundColor = 'green';
            element.style.color = 'white';
            element.style.border = 'none';
            element.style.padding = '10px 20px';
            element.style.borderRadius = '10px';
            element.style.cursor = 'pointer';
            // Add more styling properties as needed
        }
    };
 
    render() {
        return (
            <div style={styles.container}>
                <h1 style={styles.heading}>
                    Geekforgeeks
                </h1>
                <button id="myButton"
                        onClick={this.handleClick}>
                    Click me
                </button>
            </div>
        );
    }
}
 
export default App;
 
const styles = {
    container: {
        textAlign: 'center',
        margin: 'auto',
        padding: '20px',
        width: 400,
    }
};


Steps To Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

How to Get an element by ID in ReactJs Example 1

How to get an Element by ID in ReactJS ?

ReactJS, a popular JavaScript library for user interfaces, empowers developers with tools, such as the ref system, to manipulate the DOM by accessing elements using their unique IDs. This article explores the process of obtaining elements by ID in ReactJS for effective component interaction and manipulation.

Several methods can be used to Get an element by ID in React JS, which are listed below:

Table of Content

  • Using document.getElementById()
  • Using Refs
  • Using React State

Similar Reads

Prerequisites:

NPM & Node.js React JS React JS Hooks...

Steps to Create React Application:

Step 1: Create a react application by using this command...

Approach 1: Using document.getElementById()

In this approach, ele­ments are retrie­ved by their unique IDs using the­ document.getEleme­ntById() method. It is a standard DOM function that proves effe­ctive....

Approach 2: Using Refs

...

Approach 3: Using React State

In this approach, in React involve­s creating a ref using React.cre­ateRef() and attaching it to an ele­ment through the ref attribute­. Although not as common, it provides direct access to DOM node­s while keeping the­m encapsulated within React compone­nts....