Portals

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, 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".

  1. use yew::{html, create_portal, function_component, Children, Properties};
  2. #[derive(Properties, PartialEq)]
  3. pub struct ModalProps {
  4. #[prop_or_default]
  5. pub children: Children,
  6. }
  7. #[function_component(Modal)]
  8. fn modal(props: &ModalProps) -> Html {
  9. let modal_host = gloo_utils::document()
  10. .get_element_by_id("modal_host")
  11. .expect("a #modal_host element");
  12. create_portal(
  13. html!{ {for props.children.iter()} },
  14. modal_host.into(),
  15. )
  16. }

Further reading