![]() |
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 Prerequisites: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 Structure: The updated dependencies in package.json file will look like: "dependencies": { 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: Below is the code example of the above approach.
Steps To Run Application: Run the application using the following command from the root directory of the project: npm start Output: Approach 2: Using RefsIn 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: Below is the code example of the above approach.
Steps To Run Application: Run the application using the following command from the root directory of the project: npm start Output: Approach 3: Using React StateIn 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) => ({ Example: Below is the code example of the above approach.
Steps To Run Application: Run the application using the following command from the root directory of the project: npm start Output: |
Reffered: https://www.geeksforgeeks.org
ReactJS |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |