·
1 min read

Vue Tip: Use Teleport to Render a Component in a Different Place

Vue Tip: Use Teleport to Render a Component in a Different Place Image

The built-in Vue 3 Teleport component allows us to render HTML outside the Vue.js application. This can be useful to position modals, toast notifications, overlays, and more.

Sometimes, a component's template belongs logically to the component itself. At the same time, from a technical point of view, moving this part of the template elsewhere in the DOM, outside of the Vue app, would be preferable.

A full-screen modal is a common scenario where you'd want to handle the modal's logic inside the component, but it should be positioned at a completely different place.

Teleport provides a clean way to allow us to control under which parent in the DOM we want a piece of HTML to be rendered, without having to resort to a global state or splitting this into two components:

<template> <teleport to="body"> This will be appended to the body tag </teleport> </template>

The to attribute should be a valid CSS selector outside the Vue application.

Read more about Teleport in the official documentation.

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.