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

What are portals in React and when do we need them?

Câu trả lời

React Portals provide a method for rendering components into a DOM node that exists outside the usual DOM hierarchy of the parent component. This feature is particularly useful for when UI components need to break out of their container to be positioned in different parts of the application, such as modals, tooltips, or dropdowns[1][2][3][4][5][6][8][9][10][11].

Understanding React Portals

Portals in React are used to render children components into a different part of the DOM tree, bypassing the normal flow. This is achieved using the ReactDOM.createPortal() method, which takes two arguments: the JSX to be rendered and the DOM node to render into[1][2][3][4][5][6][8][9][10][11]. This method allows the rendered children to act like normal React children in terms of context and event bubbling, even though they are not physically located within the main DOM hierarchy[8].

Use Cases for React Portals

  1. Modals: Portals are ideal for modal dialogs that need to cover the entire screen or break out of a component visually contained by a parent with CSS properties like overflow: hidden or specific z-index values[1][2][3][4][5][6][8][9][10][11].

  2. Tooltips: For tooltips that need to float over other elements without being clipped by an ancestor's boundaries, portals provide a practical solution[1][2][3][4][5][6][8][9][10][11].

  3. Hovercards: Similar to tooltips, hovercards can be rendered using portals to appear over other content without disruption[1][2][3][4][5][6][8][9][10][11].

  4. Third-party Integrations: When integrating third-party DOM structures, such as widgets or UI kits that operate outside the React component tree, portals can render these elements appropriately without embedding them directly within the React DOM tree[2][5].

Advantages of Using React Portals

  • Flexibility in Placement: Portals provide the flexibility ...
junior

junior

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

junior

What are the differences between a Class component and Functional component?

entry

What are props in React?

senior

Explain the Virtual DOM concept in React

Bình luận

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

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