"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Select DOM Elements in React: Alternatives to `document.getElementById()`?

How to Select DOM Elements in React: Alternatives to `document.getElementById()`?

Published on 2024-12-22
Browse:473

How to Select DOM Elements in React:  Alternatives to `document.getElementById()`?

How to Select a DOM Element in React? What is the Equivalent of document.getElementById() in React

In React, unlike working with vanilla JavaScript, accessing DOM elements directly is different. React uses a virtual DOM to efficiently update the real DOM, this makes it different from vanilla JavaScript.

How to Access a DOM Element

Option 1: Using Refs

  • Use Refs with Function Components:(v16.8.0) Use useRef and forwardRef. Define the ref with useRef and then forward it to the DOM element using forwardRef. To access the element, use the current property of the ref (ref.current).

Option 2: Using React.createRef (v16.3 )

  • Create a ref using React.createRef() and attach it to an element to access it later. Use ref.current to get the DOM node.

Option 3: Using Callback Pattern (Legacy)

  • Define the ref attribute in the JSX element and pass a callback function that receives the reference to the DOM element.

Option 4: Using String Refs (Legacy)

  • Use string refs by setting the ref attribute to a string identifying the DOM element. Access the element using this.refs.[stringRef].

Example

Below is an example of using the callback pattern to select a DOM element:

  render() {
    return (
      

To access the elements, you can use this.progressBars[0], this.progressBars[1], and this.progressBars[2] to perform operations on them.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3