Home > Web Front-end > JS Tutorial > How to Select DOM Elements in React: Alternatives to `document.getElementById()`?

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

DDD
Release: 2024-12-04 06:21:11
Original
631 people have browsed it

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 (
      <div>
        <Progressbar
          completed={25}
         >
Copy after login

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

The above is the detailed content of How to Select DOM Elements in React: Alternatives to `document.getElementById()`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template