top of page
Logo der Online Agentur mdwp

Portals

React JS Portals provide an effective way to insert child components into a DOM node outside the current DOM hierarchy (like a child component attaching to a DOM node present in a completely different location than the parent).

This doesn't mean that a portal will break the React data flow. Despite the physical location (in the sense of the DOM tree), a portal will still inherit the context as expected.

Portals are commonly used for implementing functionalities like modals or popups, tooltips, event-triggered widgets like lightboxes, etc., which may need to break out from the current physical DOM tree.

You can create a portal using `ReactDOM.createPortal(child, container)` where:

'child' is any renderable React child, such as an element, string, or fragment.

'container' is a DOM node.

Here's a basic code example:
```javascript
import React from "react";
import ReactDOM from "react-dom";

class Modal extends React.Component {
constructor(props) {
super(props);
this.el = document.createElement("div");
}

componentDidMount() {
document.body.appendChild(this.el);
}

componentWillUnmount() {
document.body.removeChild(this.el);
}

render() {
return ReactDOM.createPortal(
this.props.children,
this.el
);
}
}

// In a component
function App() {
return (
<div>
<Modal>
<h1>I am a modal!</h1>
</Modal>
</div>
);
}

export default App;
```
In this example, a `<Modal />` component attaches its children into a div that it creates and appends to the document body. Outside components render this `<Modal />` component and pass in their children (the contents of the modal).

bottom of page