Middle
Tell me, what are portals used for in React?
sobes.tech AI
Answer from AI
React portals allow rendering child components into a DOM node that exists outside the hierarchy of the parent component. This is useful when you need to display an element above others, such as modal windows, tooltips, or pop-up menus, to avoid issues with CSS styles, z-index, or positioning.
Example of using a portal:
import React from 'react';
import ReactDOM from 'react-dom';
function Modal({ children }) {
return ReactDOM.createPortal(
<div className="modal">
{children}
</div>,
document.getElementById('modal-root')
);
}
Here, the content of the modal window will be rendered into the element with id "modal-root", which can be outside the main application root.