Overview
The Svelte component for rendering outside the DOM of the parent component allows users to create a portal to render components outside of their parent component’s DOM. This functionality was borrowed from an idea discussed in the Svelte repository. The component can be installed and used easily and also supports TypeScript.
Features
- Portal component: The component allows for rendering components outside of the parent component’s DOM. It has a single property called
target, which can be either an HTMLElement or a CSS selector. - Target property: The
targetproperty specifies the element where the component should be rendered. It can be specified as an HTMLElement usingtarget={document.body}or as a CSS selector usingtarget="#modals". - Default target: If no target is given, the component defaults to rendering in the
document.body. - Portal action: Users can also use a svelte action to apply the portal functionality directly to DOM elements.
- Hidden attribute: The
hiddenattribute is only needed when using server-side rendering (SSR). When the portal component moves an element to its target location, it removes the hidden attribute. - TypeScript support: For TypeScript users, they should import from “svelte-portal/src/Portal.svelte” instead of “svelte-portal” to get proper typing support.
Installation
To install the Svelte component for rendering outside the DOM of the parent component, follow these steps:
- Install the package using your preferred package manager:
npm install svelte-portal
or
yarn add svelte-portal
- Import the component in your Svelte file:
import Portal from "svelte-portal";
- Use the component in your Svelte template:
<Portal />
Summary
The Svelte component for rendering outside the DOM of the parent component is a useful tool for creating portals and rendering components outside of their parent component’s DOM. It provides a simple and flexible API for specifying the target element, and also supports TypeScript for better type checking.