Teleporting to Nowhere

🗓 March 22, 2024



The Teleport Component in Vue is rad. It's really handy for chucking some content into a specific part your dom from anywhere else you might be.

I use it in a navigation component, where I designate a <div id="mobile-nav-extras"></div> as an area where other components can add to the mobile nav if needed. This is super helpful when your nav might change based on the context of your app.

But then I ran into this error:

TypeError: component is null



The call stack in the surrounding error wasn't very helpful, so I ended up commenting out sections of my page until I found the culprit... the <Teleport to="#mobile-nav-extras"> component!

The Problem

So it turns out my <div id="mobile-nav-extras"></div> was actually tucked under a v-if in one of it's parent elements, like so:

<section v-if="loggedIn">
  <div id="mobile-nav-extras"></div>
</section>



Now the problem is pretty clear... I was telling the Teleport to send my component to an element that did not exist.

I was telling it to teleport to nowhere.

The Solution

Pretty easy. Just make sure the whatever you set in the to prop on the Teleport actually exists. In my case, I added a matching v-if to my "caller", like this:

<Teleport
  v-if="loggedIn"
  to="#mobile-nav-extras"
>
  <p>all fixed :)</p>
</Teleport>