Teleport
Teleport is a built-in component that allows us to "teleport" a part of a component's template into a DOM node that exists outside the DOM hierarchy of that component.
The most common use cases for Teleport are Modals, Tooltips, and Popovers.
Basic Usage
To use Teleport, wrap your content with the <Teleport> component and specify a to target. The target can be a CSS selector string or an actual DOM element.
html
<script setup>
import { signal } from 'nexa-framework'
const showModal = signal(false)
</script>
<template>
<button @click="showModal.value = true">Open Modal</button>
<Teleport to="body">
<div v-if="showModal.value" class="modal">
<p>I am a teleported modal!</p>
<button @click="showModal.value = false">Close</button>
</div>
</Teleport>
</template>
<style>
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
padding: 20px;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
</style>Why Teleport?
When building components like modals, we often want them to be rendered at the end of the <body> to avoid issues with:
- z-index: If the parent has a low
z-index, the modal might be hidden behind other elements. - overflow: hidden: If the parent has
overflow: hidden, the modal might be clipped. - Staking Context: CSS transforms or filters on parent elements can create new stacking contexts that affect the modal.
With <Teleport>, the modal remains logically a child of your component (it can access the component's state), but it is physically rendered elsewhere.