Home > Web Front-end > JS Tutorial > How Can I Access DOM Elements in React?

How Can I Access DOM Elements in React?

Susan Sarandon
Release: 2024-12-01 02:26:08
Original
1001 people have browsed it

How Can I Access DOM Elements in React?

Accessing DOM Elements in React

How to Get DOM Elements in React?

In React, accessing DOM elements is not as straightforward as using getElementById() in traditional JavaScript. React handles DOM manipulation differently, prioritizing performance and virtual DOM diffing.

React Refs

To access DOM elements in React, you need to use refs. Refs are a way for React to maintain a reference to a DOM element created by a React component. There are multiple ways to create refs in React:

  • String Refs (Legacy):
    In older versions of React, you could use string refs to access elements by setting the ref attribute to a string. However, this approach is discouraged and may be removed in future versions.
  • Callback Refs:
    A recommended approach is to use callback refs. With callback refs, you pass a callback function as the value of the ref attribute. The function receives the DOM element as its argument.

    Example:

    <Progressbar completed={25}>
    Copy after login
  • React.createRef (Functional Components):
    For functional components introduced in React 16.8, you can use React.createRef(). This returns a ref object that you can assign to an attribute.

    Example:

    const myRef = React.createRef();
    
    const handleClick = () => {
      const node = myRef.current;
    }
    
    return <div ref={myRef} onClick={handleClick} />;
    Copy after login

Accessing the Element

Once you have created a ref, you can access the DOM element as follows:

  • Legacy String Refs:
    this.refs.elementName
  • Callback Refs:
    this.elementName
  • React.createRef:
    refObject.current

For example:

const node = this.refs.Progress1;
const node = this.Progress[0];
const node = myRef.current;
Copy after login

In your specific case, you can use callback refs to access the progress bar elements and perform the handleClick10 function:

handleClick10 = (e) => {
    const progressElement = this.refs[this.state.baction];
    if (progressElement) {
        progressElement.addPrecent(10);
    }
};
Copy after login

The above is the detailed content of How Can I Access DOM Elements in React?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template