Portals in React allow rendering elements outside their parent DOM node while preserving the React context. They are useful for rendering elements like modals, tooltips, and other interactive components that need to appear at a higher level in the DOM tree.
Creating portals in React:
- Using
ReactDOM.createPortal
to render an element outside its parent:
import React from 'react'; import ReactDOM from 'react-dom'; const modalRoot = document.getElementById('modal-root'); class Modal extends React.Component { render() { return ReactDOM.createPortal( this.props.children, modalRoot ); } }
- Using the portal in an application:
class App extends React.Component { render() { return ( <div> <h1>My App</h1> <Modal> <div className="modal"> <p>This is a modal!</p> </div> </Modal> </div> ); } }
Benefits of portals:
- Component isolation: Portals allow for isolating components like modals from the rest of the application.
- Flexible rendering: They enable rendering components anywhere in the DOM tree, which is particularly useful for interactive components.
- Context preservation: Although components rendered through a portal are located in a different place in the DOM tree, they preserve the React context, including state and props.
Portals are a powerful tool in React, enabling flexible management of component rendering within an application.