Kaede Hoshikawa ac3af0a9bc
Suspense Support (#2212)
* Make Html a Result.

* Fix tests.

* Implement Suspense.

* Schedule render when suspension is resumed.

* Shift children into a detached node.

* styled example.

* Update wording a little bit.

* Move hint to hint.

* Add some tests.

* Fix clippy.

* Add docs.

* Add to sidebar.

* Fix syntax highlight.

* Component -> BaseComponent.

* Html -> VNode, HtmlResult = RenderResult<Html>.

* Suspendible Function Component.

* Add a method to create suspension from futures.

* Revert extra changes.

* Fix tests.

* Update documentation.

* Switch to custom trait to make test reliable.

* Fix file permission.

* Fix docs.

* Remove log.

* Fix file permission.

* Fix component name error.

* Make Suspension a future.
2022-01-05 18:16:34 +05:00

42 lines
1.7 KiB
Plaintext

---
title: "Portals"
description: "Rendering into out-of-tree DOM nodes"
---
## How to think about portals?
Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
`yew::create_portal(child, host)` returns a `Html` value that renders `child` not hierarchically under its parent component,
but as a child of the `host` element.
## Usage
Typical uses of portals can include modal dialogs and hovercards, as well as more technical applications such as controlling the contents of an element's [`shadowRoot`](https://developer.mozilla.org/en-US/docs/Web/API/Element/shadowRoot), appending stylesheets to the surrounding document's `<head>` and collecting referenced elements inside a central `<defs>` element of an `<svg>`.
Note that `yew::create_portal` is a rather low-level building block, on which other components should be built that provide the interface for your specific use case. As an example, here is a simple modal dialogue that renders its `children` into an element outside `yew`'s control, identified by the `id="modal_host"`.
```rust
use yew::{html, create_portal, function_component, Children, Properties, Html};
#[derive(Properties, PartialEq)]
pub struct ModalProps {
#[prop_or_default]
pub children: Children,
}
#[function_component(Modal)]
fn modal(props: &ModalProps) -> Html {
let modal_host = gloo::utils::document()
.get_element_by_id("modal_host")
.expect("a #modal_host element");
create_portal(
html!{ {for props.children.iter()} },
modal_host.into(),
)
}
```
## Further reading
- [Portals example](https://github.com/yewstack/yew/tree/master/examples/portals)