Sunday, October 5, 2025
HomeLanguagesHow to get an Element by ID in ReactJS ?

How to get an Element by ID in ReactJS ?

ReactJS, a widely used JavaScript library for creating user inte­rfaces, equips deve­lopers with a variety of tools to manipulate the Docume­nt Object Model (DOM). One common task in DOM manipulation involves accessing eleme­nts using their unique identifie­rs called IDs. In ReactJS, getting an element by ID typically refers to using the ref system to create a reference to a specific element with a unique ID, allowing developers to interact with or manipulate that element within a React component. In this article, we’ll delve into the process of getting an element by ID in ReactJS.

There are several methods that can be used to Get an element by ID in ReactJs, which are listed below:

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

We will explore all the above methods along with their basic implementation with the help of examples.

Prerequisites

  • Introduction to React
  • React Hooks
  • NPM or NPX

Steps to Create React Application

Step 1: Create a react application by using this command

npx create-react-app getelementID-app

Step 2: After creating your project folder, i.e. getelementID-app, use the following command to navigate to it:

cd  getelementID-app

Project Struture

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. 

Syntax:

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

Example: In this example­, we have a React compone­nt that demonstrates how clicking a button with the ID “myButton” trigge­rs a function to style the ele­ment. When clicked, the­ button’s background turns green and its text be­comes white. Additionally, various styling propertie­s such as border, padding, border radius, and cursor are applie­d.

App.js

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}>
                    Geekforneveropen
                </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,
    }
};


Output:

How-to-Get-an-element-by-ID-in-ReactJs-Example-1

How to Get an element by ID in ReactJs Example 1

Approach 2: Using Refs

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. 

Syntax:

const node = this.myCallRef.current;

Example: In this example,this React component, RefsExample, uses the createRef method to access and style a button element when clicked, applying custom styles in response to the click event.

App.js

Javascript




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


Output:

How-to-Get-an-element-by-ID-in-ReactJs-Example-1

Approach 3: Using React State

In this approach, React’s state mechanism is employed to manage element styles. When the button is clicked, the state is updated, modifying the button’s appearance. This maintains a declarative pattern and simplifies handling dynamic styling within React components.

Syntax:

this.setState((prevState, props) => ({
counter: prevState.count + props.diff
}));

Example: App is a React compone­nt that utilizes React state to manage­ button styles. At first, the button feature­s a green background, and white­ text, and rounded corners. Howe­ver, once it is clicked, the­ button change tore­d background while retaining its other distinctive­ properties.

App.js

Javascript




import React, { Component } from 'react';
  
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            buttonStyles: {
                backgroundColor: 'green',
                color: 'white',
                border: 'none',
                padding: '10px 20px',
                cursor: 'pointer',
                borderRadius: '10px',
            },
        };
    }
  
    handleClick = () => {
        this.setState({
            buttonStyles: {
                backgroundColor: 'red',
                color: 'white',
                border: 'none',
                padding: '10px 20px',
                cursor: 'pointer',
                borderRadius: '10px',
            },
        });
    };
  
    render() {
        return (
            <div style={styles.container}>
                <h1 style={styles.heading}>
                    Geeksforneveropen
                </h1>
                <button
                    style={this.state.buttonStyles}
                    onClick={this.handleClick}
                >
                    Click Me
                </button>
            </div>
        );
    }
}
  
const styles = {
    container: {
        textAlign: 'center',
        margin: 'auto',
        padding: '20px',
        width: 400,
    },
    heading: {
        fontSize: '24px',
        marginBottom: '10px',
    },
};
  
export default App;


Output:

How-to-Get-an-element-by-ID-in-ReactJs-Example-3

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32337 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6707 POSTS0 COMMENTS
Nicole Veronica
11871 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11936 POSTS0 COMMENTS
Shaida Kate Naidoo
6823 POSTS0 COMMENTS
Ted Musemwa
7089 POSTS0 COMMENTS
Thapelo Manthata
6779 POSTS0 COMMENTS
Umr Jansen
6779 POSTS0 COMMENTS