How to not render <Portal> if mount is undefined?

It seems <Portal> always insert to document.body if the mount is null. But I only want to render the mount has element.
3 Replies
Wurfle
Wurfle16mo ago
You can wrap the Portal in a Show. Passing the element to the when attribute to ensure that it is not null.
musiclover
musiclover16mo ago
Yes, but Can I make document.getElementById reactive?
Wurfle
Wurfle16mo ago
document.getElementById only returns an element at a particular moment in time. You could run getElementById inside createEffect and then update a signal with the result:
const [element, setElement] = createSignal()

// This only runs once unless you access some other signal in it.
createEffect(() => {
setElement(document.getElementById("foo"))
})
const [element, setElement] = createSignal()

// This only runs once unless you access some other signal in it.
createEffect(() => {
setElement(document.getElementById("foo"))
})
Its worth noting that if foo gets removed from the DOM for whatever reason, your signal will not be updated of this unless the effect runs again. Alternatively you could use the ref inherent attribute, but this only works for elements created with JSX:
const [element, setElement] = createSignal()

return <div ref={setElement}>Foo</div>
const [element, setElement] = createSignal()

return <div ref={setElement}>Foo</div>
Want results from more Discord servers?
Add your server
More Posts