Portal
Renders children into a different part of the DOM tree. Useful for modals, tooltips, and dropdowns.
Portal is unmounted
document.body
custom element
#Installation
bunx --bun barefoot add portal#Usage
1import { createPortal } from '@barefootjs/dom'23// Mount content at document.body4const portal = createPortal('<div>Portal content</div>')56// Mount at a specific container7const portal = createPortal('<div>Content</div>', containerEl)89// Cleanup10portal.unmount()#Examples
#Basic
1"use client"23import { createSignal, createPortal } from '@barefootjs/dom'45function PortalBasic() {6 const [open, setOpen] = createSignal(false)7 let portal = null89 const showPortal = () => {10 portal = createPortal(11 '<div class="modal">Portal content at document.body</div>'12 )13 setOpen(true)14 }1516 const hidePortal = () => {17 portal?.unmount()18 portal = null19 setOpen(false)20 }2122 return (23 <div>24 <button onClick={showPortal} disabled={open()}>25 Show Portal26 </button>27 </div>28 )29}#Custom Container
Portal container (empty)
1"use client"23import { createSignal, createPortal } from '@barefootjs/dom'45function PortalCustomContainer() {6 const [open, setOpen] = createSignal(false)7 let portal = null8 let containerRef = null910 const showPortal = () => {11 if (!containerRef) return12 portal = createPortal(13 '<div>Rendered inside custom container</div>',14 containerRef // Custom container element15 )16 setOpen(true)17 }1819 return (20 <div>21 <button onClick={showPortal}>Show in Container</button>22 <div ref={(el) => containerRef = el}>23 {/* Portal will render here */}24 </div>25 </div>26 )27}#API Reference
createPortal(children, container?)
Creates a portal to mount content at a specific container. Returns a Portal object with element reference and unmount method.
Parameters
| Prop | Type | Default | Description |
|---|---|---|---|
| children | HTMLElement | string | Renderable | - | Content to mount in the portal. Can be an HTMLElement, HTML string, or object with toString() method (like JSX). |
| container | HTMLElement | document.body | Target container element where the portal content will be mounted. |
Return Value
| Prop | Type | Default | Description |
|---|---|---|---|
| element | HTMLElement | - | Reference to the mounted DOM element. |
| unmount | () => void | - | Function to remove the portal content from the DOM. Safe to call multiple times. |