Portals
Normally when rendering child components, the generated markup is nested exactly where the child component is. Take the following JSX snippet for example.
class Child extends JSXComponent {
render() {
return <div class="child"></div>;
}
}
class Parent extends JSXComponent {
render() {
return <div class="parent">
<Child />
</div>
}
}
// Resulting markup
<div class="parent"><div class="child"></div></div>
But what if you need to render the component elsewhere? Occasionally it's necessary to render a child component outside the DOM hierarchy of the parent component. This is where Portals come in.
class Child extends JSXComponent {
render() {
return <div class="child"></div>;
}
}
class Parent extends JSXComponent {
render() {
return <div class="parent">
<Child portalElement={document.getElementById('target')} />
</div>
}
}
Now the markup of Child
will be rendered to the #target
element on the page, but will still receive updates from any data being passed from Parent
. It will also be disposed and detached from the page along with it's parent.
This is especially useful when creating components such as modals, dropdowns, tooltips, or any component that needs to always overlay other pieces of content.