25. What are portals in React and how do you use them?

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:

  1. 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 ); } }
  1. 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:

  1. Component isolation: Portals allow for isolating components like modals from the rest of the application.
  2. Flexible rendering: They enable rendering components anywhere in the DOM tree, which is particularly useful for interactive components.
  3. 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.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.