Skip to content

Commit 4f87cfe

Browse files
committed
fix: portal fails gracefully if target doesn't exist
1 parent cb464dc commit 4f87cfe

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

src/lib/actions/portal.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,18 @@
22
* Usage: `<div use:portal>` or `<div use:portal={'#direction'}>`, add `hidden` if SSR rendered (requires updating action with node.hidden = false and true)
33
*/
44
export function portal(node: HTMLElement, target = 'body') {
5-
const portal = document.createElement('div');
6-
document.querySelector(target).appendChild(portal);
7-
portal.appendChild(node);
5+
const target_div = document.querySelector(target)
6+
if (!target_div)
7+
return
8+
9+
const portal = document.createElement('div')
10+
target_div.appendChild(portal)
11+
portal.appendChild(node)
812

913
return {
1014
destroy() {
11-
portal.parentElement.removeChild(portal);
15+
portal.parentElement.removeChild(portal)
1216
},
13-
};
17+
}
1418
}
1519
// from https://github.com/romkor/svelte-portal

0 commit comments

Comments
 (0)