Skip to content

Latest commit

 

History

History
46 lines (35 loc) · 2.08 KB

12.ReactPortals.md

File metadata and controls

46 lines (35 loc) · 2.08 KB

Easily Render Components Anywhere with React Portals

React portals are a way to render a React component to a different DOM element than the parent component. Portals can be useful in a variety of situations, such as:

  • Modals: You can use portals to render a modal or pop-up window that is separate from the rest of the page. This can be helpful for maintaining the focus and structure of the main page while displaying a separate piece of content.

  • Overlays: You can use portals to render an overlay or overlay element that is separate from the main content of the page. This can be useful for displaying a loading spinner or a message that needs to be displayed over the main content.

  • DOM manipulation: You can use portals to manipulate the DOM in a way that is not possible with the standard React rendering model. For example, you can use portals to append elements to the body of the page, or to render elements outside of the root element of your application.

To use portals in your React application, you can use the ReactDOM.createPortal function. Here's an example of how you might use a portal to render a modal:

  • First Argument is JSX
  • Second argument conatins the attachment of element class or id
import React from "react";
import ReactDOM from "react-dom";

function Modal(props) {
  return ReactDOM.createPortal(
    <div className="modal">
      <button onClick={props.onClose}>Close</button>
      {props.children}
    </div>,
    document.geElementByID("modelWindow")
  );
}

function App() {
  const [isModalOpen, setIsModalOpen] = React.useState(false);

  return (
    <div>
      <button onClick={() => setIsModalOpen(true)}>Open modal</button>
      {isModalOpen && (
        <Modal onClose={() => setIsModalOpen(false)}>
          <h1>Modal content</h1>
        </Modal>
      )}
    </div>
  );
}

In this example, the Modal component uses the ReactDOM.createPortal function to render a modal element to the document.body element. When the modal is opened, it is rendered outside of the App component, allowing it to be displayed over the main content of the page.