ReactJS, a widely used JavaScript library for creating user interfaces, equips developers with a variety of tools to manipulate the Document Object Model (DOM). One common task in DOM manipulation involves accessing elements using their unique identifiers 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, 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: In this example, we have a React component that demonstrates how clicking a button with the ID “myButton” triggers a function to style the element. When clicked, the button’s background turns green and its text becomes white. Additionally, various styling properties such as border, padding, border radius, and cursor are applied.
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
Approach 2: Using Refs
In this approach, in React involves creating a ref using React.createRef() and attaching it to an element through the ref attribute. Although not as common, it provides direct access to DOM nodes while keeping them encapsulated within React components.
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:
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 component that utilizes React state to manage button styles. At first, the button features a green background, and white text, and rounded corners. However, once it is clicked, the button change tored 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: