From 4f87cfe09c2aed421b904e5990bd42b0e843a28a Mon Sep 17 00:00:00 2001 From: jacob-8 Date: Fri, 26 Jul 2024 13:53:39 +0800 Subject: [PATCH] fix: portal fails gracefully if target doesn't exist --- src/lib/actions/portal.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/lib/actions/portal.ts b/src/lib/actions/portal.ts index d269c6d..b4bb46a 100644 --- a/src/lib/actions/portal.ts +++ b/src/lib/actions/portal.ts @@ -2,14 +2,18 @@ * Usage: `
` or `
`, add `hidden` if SSR rendered (requires updating action with node.hidden = false and true) */ export function portal(node: HTMLElement, target = 'body') { - const portal = document.createElement('div'); - document.querySelector(target).appendChild(portal); - portal.appendChild(node); + const target_div = document.querySelector(target) + if (!target_div) + return + + const portal = document.createElement('div') + target_div.appendChild(portal) + portal.appendChild(node) return { destroy() { - portal.parentElement.removeChild(portal); + portal.parentElement.removeChild(portal) }, - }; + } } // from https://github.com/romkor/svelte-portal