What are React Portals and why are they used?

🚀 React Toughest Interview Question #16 Q16: What are React portals and why are they used? Answer: React portals provide a way to render children into a DOM node that exists outside the parent component’s DOM hierarchy. They are created using: ReactDOM.createPortal(child, container) Example: function Modal({ children }) { return ReactDOM.createPortal( <div className="modal">{children}</div>, document.getElementById('modal-root') ); } Why use Portals? ✅ For rendering components like modals, tooltips, or dropdowns that should visually appear above everything else. ✅ Helps avoid CSS z-index and overflow issues caused by nesting. ✅ Keeps React component structure logical while allowing flexible DOM placement. Pro Tip: Even though portals render outside the DOM tree, events still bubble up through the React tree — maintaining consistent event handling. #React #JavaScript #Frontend #WebDevelopment #InterviewQuestions #ReactJS #UI #TechCareers

To view or add a comment, sign in

Explore content categories