React is a powerful JavaScript library for building user interfaces. In React, components are the basic unit for building UI, and rendering of components will eventually produce corresponding DOM elements. Sometimes, developers need to obtain the DOM elements corresponding to the component for direct operation, such as adding event listening, getting the element's size, scrolling position, etc. In this article, we will dive into several ways to get the DOM elements corresponding to a component in React, including using refs, callbacks, and how to handle DOM elements in a function component.
1. Understand the DOM in React
In React, the rendering result of a component is a virtual DOM (Virtual DOM), which is the key to React's performance improvement. When the state or properties of the component change, React creates a new virtual DOM and compares it with the previous virtual DOM, and then updates the changed part to the actual DOM.
Although React encourages the use of its declarative API to build UIs, in some cases it is necessary to manipulate the DOM directly. At this time, we need to obtain the actual DOM element corresponding to the component.
2. Use Refs
React provides a way to reference the DOM element corresponding to the component, which is refs. Refs is a way to directly access instances of DOM elements or class components. Here are detailed instructions on how to use refs.
2.1 Create a Ref
In class components, use()
to create a ref.
import React, { Component } from 'react'; class MyComponent extends Component { constructor(props) { super(props); = (); // Create a ref } componentDidMount() { // Access DOM elements (); // Output the corresponding DOM element } render() { return <div ref={}>Hello, World!</div>; // Assign ref to DOM element } } export default MyComponent;
In the example above,myRef
Created and assigned to the componentdiv
Elements. Then incomponentDidMount
In the life cycle method, we can useAccess the corresponding DOM element.
2.2 Refs in function components
In function components, you can useuseRef
Hook to create refs.useRef
Allows us to keep references to DOM elements in function components.
import React, { useRef, useEffect } from 'react'; const MyComponent = () => { const myRef = useRef(null); // Create a ref useEffect(() => { (); // Output the corresponding DOM element }, []); return <div ref={myRef}>Hello, World!</div>; // Assign ref to DOM element}; export default MyComponent;
Here,myRef
It is useduseRef
Created,exist
useEffect
The real DOM element can be accessed in the hook.
3. Callback Refs
In addition to usingcreateRef
anduseRef
, React also allows the use of callback refs. This approach is very useful when dynamic refs are required.
3.1 Using callbacks Refs
Callback refs is a function that takes DOM elements as parameters and can be updated dynamically throughout the life of the component.
import React, { Component } from 'react'; class MyComponent extends Component { constructor(props) { super(props); = null; // Initialize ref } setRef = (element) => { = element; // Assign the DOM element to myRef }; componentDidMount() { (); // Output the corresponding DOM element } render() { return <div ref={}>Hello, World!</div>; // Use callback ref } } export default MyComponent;
In this example,setRef
Functions are used as callbacks, when the DOM element is created,setRef
Will be called and the element will be assigned to。
3.2 Callbacks in function components Refs
In function components, callback refs can also be used. As shown below:
import React, { useEffect } from 'react'; const MyComponent = () => { let myRef = null; // Initialize ref const setRef = (element) => { myRef = element; // Assign the DOM element to myRef }; useEffect(() => { (myRef); // Output the corresponding DOM element }, []); return <div ref={setRef}>Hello, World!</div>; // Use callback ref}; export default MyComponent;
In this example,setRef
Used as a callback whendiv
When rendered,myRef
The corresponding DOM element reference will be held.
4. Get multiple DOM elements
In some cases, multiple DOM elements may be required. For example, when rendering a list, each element can be accessed individually using refs.
4.1 Refs using arrays
In a class component, refs can be stored as an array:
import React, { Component } from 'react'; class MyComponent extends Component { constructor(props) { super(props); = []; // Initialize an empty array } addRef = (element) => { if (element && !(element)) { (element); // Add DOM elements to the array } }; componentDidMount() { (); // Output all corresponding DOM elements } render() { return ( <div> {['Item 1', 'Item 2', 'Item 3'].map((item, index) => ( <div key={index} ref={}> {item} </div> ))} </div> ); } } export default MyComponent;
In this example,itemsRef
The array stores all rendereddiv
Elements.
4.2 Using useRef and Map
In function components, useuseRef
and Map can achieve the same effect:
import React, { useRef, useEffect } from 'react'; const MyComponent = () => { const itemsRef = useRef(new Map()); // Create a Map const setRef = (element, index) => { if (element) { (index, element); // Save the DOM element into the Map } }; useEffect(() => { (); // Output all corresponding DOM elements }, []); return ( <div> {['Item 1', 'Item 2', 'Item 3'].map((item, index) => ( <div key={index} ref={(el) => setRef(el, index)}> {item} </div> ))} </div> ); }; export default MyComponent;
Here,itemsRef
is a map that can store index maps of each DOM element.
5. Notes on direct operation of DOM elements
Although DOM elements can be accessed and manipulated directly in React, you should try to avoid this. React is a declarative library that directly manipulating the DOM may cause conflicts with React's state management.
5.1 Keep the component declarative
In React, you should usually control the UI through state and properties rather than manipulating the DOM directly. When it is necessary to change the appearance or behavior of a component, the status or properties associated with it should be updated.
5.2 Occasions where refs are used
In some cases, it is appropriate to use refs, such as:
- Need to integrate with third-party libraries.
- Need to directly control focus, text selection, or media playback.
- The underlying DOM API is required in the animation.
5.3 Avoid unnecessary re-rendering
When using refs to manipulate the DOM, make sure to avoid unnecessary re-rendering. If you arerender()
Modifying the DOM directly in the method rather than updating the status of React may cause the desynchronization between the virtual DOM of React and the actual DOM.
6. Practical application examples
Here is a more complete example of how to use refs in a real application to get DOM elements.
6.1 Create a simple input box component
We will create an input box component that contains a button that will get focus when the button is clicked.
import React, { useRef } from 'react'; const InputComponent = () => { const inputRef = useRef(null); // Create a ref const focusInput = () => { (); // Make the input box focus }; return ( <div> <input ref={inputRef} type="text" placeholder="Enter some text..." /> <button onClick={focusInput}>Focus input box</button> </div> ); }; export default InputComponent;
In this example, when the user clicks the Focus Input Box button, the input box gets focus. This is achieved through refs,()
The DOM was called directlyfocus()
method.
7. Summary
In React, getting the DOM elements corresponding to the component is a very important skill, especially when you need to operate the DOM directly. Using refs is the standard way to access DOM. Whether in class components or function components, refs allows developers to easily obtain and manipulate DOM elements.
Through this article, you should be able to master the following content:
- How to use it in a class component
createRef
Get the DOM element. - How to use it in function components
useRef
Get the DOM element. - How to use callback refs to get DOM elements.
- How to handle refs for multiple DOM elements.
- When to manipulate DOM elements directly, and how to avoid unnecessary re-rendering.
Hopefully this knowledge will help you handle the interaction between components and DOM more confidently and efficiently in actual React development. Whether it is simple input boxes, complex animations, or integration with third-party libraries, mastering the method of obtaining DOM elements is very critical.
This is the end of this article about the various implementation methods of React obtaining the corresponding DOM elements of the component. For more relevant React obtaining the corresponding DOM elements, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!