DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

JSmith AR
JSmith AR

Posted on

[Svelte] Creating Dialog component with use:portal

If you have already used React maybe you know React Portals, this feature allows render components outside DOM hierarchy.

Svelte doesn't have a native portal feature but we can create easily an use:action to resolve this lack.

// file: portal.ts
function moveNode(node: HTMLElement, target?: HTMLElement | string) {
  if (typeof target === "string") {
    target = document.getElementById(target);
  }
  if (!target) target = document.body;

  target.appendChild(node);
}

function portal(node: HTMLElement, target?: HTMLElement | string) {
  moveNode(node, target);

  return {
    update(target) {
      moveNode(node, target);
    },
  };
}

export default portal;

the previous action move the node outside hierarchy even if the target change, also the target can be an id element or a reference to a HTMLElement as window.document.body

How to use the portal Svelte action

<script> 
import portal from "./portal";
</script>

<div id="dialog">
<!-- '<p>' will be rendered here  -->
<div/>
...
<p use:portal="dialog" />

Here is a complete example, I recommend use the inspector to check how the dialog is rendered.

Top comments (0)

๐ŸŒš Browsing with dark mode makes you a better developer.

It's a scientific fact.