Javascript is required
Mokkapps Logo

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

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Jan 9, 2022
1 min read
|
95 views
Template
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 Twitter to get notified about new tips, blog posts, and more content from me. Alternatively (or additionally), you can also subscribe to my newsletter.