How to usedocument.getElementById() in ReactJS
In this approach, elements are retrieved by their unique IDs using the document.getElementById() method. It is a standard DOM function that proves effective.
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 ?
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