Svelte: Portal

Created on 24 Jun 2019  Â·  7Comments  Â·  Source: sveltejs/svelte

is there some thing like ReactDOM.createPortal(child, container) in svelte3 ?

Most helpful comment

Hi there, here's how you can do it:

<script>
// src/components/Portal.svelte
import { onMount, onDestroy } from 'svelte'
let ref
let portal

onMount(() => {
  portal = document.createElement('div')
  portal.className = 'portal'
  document.body.appendChild(portal)
  portal.appendChild(ref)
})

onDestroy(() => {
  document.body.removeChild(portal)
})

</script>

<div class="portal-clone">
  <div bind:this={ref}>
    <slot></slot>
  </div>
</div>
<style>
  .portal-clone { display: none; }
</style>

All 7 comments

@MaxMilton How about event-bubbling-through-portals ?

1849 ?

no, that case for Svelte2

Hi there, here's how you can do it:

<script>
// src/components/Portal.svelte
import { onMount, onDestroy } from 'svelte'
let ref
let portal

onMount(() => {
  portal = document.createElement('div')
  portal.className = 'portal'
  document.body.appendChild(portal)
  portal.appendChild(ref)
})

onDestroy(() => {
  document.body.removeChild(portal)
})

</script>

<div class="portal-clone">
  <div bind:this={ref}>
    <slot></slot>
  </div>
</div>
<style>
  .portal-clone { display: none; }
</style>

Hi there, here's how you can do it:

<script>
// src/components/Portal.svelte
import { onMount, onDestroy } from 'svelte'
let ref
let portal

onMount(() => {
  portal = document.createElement('div')
  portal.className = 'portal'
  document.body.appendChild(portal)
  portal.appendChild(ref)
})

onDestroy(() => {
  document.body.removeChild(portal)
})

</script>

<div class="portal-clone">
  <div bind:this={ref}>
    <slot></slot>
  </div>
</div>
<style>
  .portal-clone { display: none; }
</style>

nice answer,thx a lot

@ThomasJuster

What is the purpose of the wrapping 'portal' element? Just curious.

Could be:

onMount(() => {
  document.body.appendChild(ref)
})

onDestroy(() => {
  document.body.removeChild(ref)
})

No?

For some reason, when the container doesn't include the previously added element, I will have the error:

TypeError: Cannot read property 'removeChild' of null

when using my version.

This error doesn't happen using @ThomasJuster 's solution

Was this page helpful?
0 / 5 - 0 ratings

Related issues

thoughtspile picture thoughtspile  Â·  3Comments

sskyy picture sskyy  Â·  3Comments

mmjmanders picture mmjmanders  Â·  3Comments

plumpNation picture plumpNation  Â·  3Comments

clitetailor picture clitetailor  Â·  3Comments