Câu hỏi phỏng vấn Reactjs
Câu hỏi

How to access DOM elements in React?

Câu trả lời

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:

Using Refs in Class Components

In class components, you can create refs using React.createRef() and attach them to elements via the ref attribute. Here’s a basic example:

javascript Copy
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.

Using Refs in Functional Components

In functional components, you use the useRef hook to create refs. The usage is slightly different because hooks rely on function closures:

javascript Copy
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.

Forwarding Refs

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:

javascript Copy
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;

Callback Refs

Another way to handle refs in React is by using callback refs. This approach provides more control over when refs are set and cleared:

javascript Copy
import React, { Component } from 'react';

class My...
junior

junior

Gợi ý câu hỏi phỏng vấn

senior

How would you go about investigating slow React application rendering?

entry

What is the use of refs ?

middle

What is the difference between createElement and cloneElement ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào