How to access DOM elements in React?
How to access DOM elements in React?
To access DOM elements in React, you primarily use the concept of "refs." Refs provide a way to access the actual DOM nodes in your React components. Here’s how you can work with refs to access DOM elements:
In class components, you can create refs using React.createRef()
and attach them to elements via the ref
attribute. Here’s a basic example:
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount() {
console.log(this.myRef.current); // Access the DOM node
}
render() {
return <div ref={this.myRef}>Hello, World!</div>;
}
}
export default MyComponent;
In this example, this.myRef.current
will point to the <div>
DOM node after the component has mounted.
In functional components, you use the useRef
hook to create refs. The usage is slightly different because hooks rely on function closures:
import React, { useRef, useEffect } from 'react';
function MyComponent() {
const myRef = useRef(null);
useEffect(() => {
console.log(myRef.current); // Access the DOM node
}, []);
return <div ref={myRef}>Hello, World!</div>;
}
export default MyComponent;
Here, myRef.current
will also point to the <div>
DOM node, and you can access it after the component renders.
Sometimes you need to access a DOM element inside a child component from a parent component. React allows you to "forward" refs from parent to child using the forwardRef
function:
import React, { useRef, forwardRef } from 'react';
const MyComponent = forwardRef((props, ref) => (
<div ref={ref}>Hello, World!</div>
));
function ParentComponent() {
const myRef = useRef(null);
useEffect(() => {
console.log(myRef.current); // Access the child's DOM node
}, []);
return <MyComponent ref={myRef} />;
}
export default ParentComponent;
Another way to handle refs in React is by using callback refs. This approach provides more control over when refs are set and cleared:
import React, { Component } from 'react';
class My...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào