Skip to main content
Version: 2.9.0

Portals

Portals provide a way to render components outside the DOM hierarchy of the parent component. Portals are often used to create dialog components in React applications.

You can create a portal component by calling the function ReactDOM.createPortal : ReactElement -> HTMLElement -> ReactElement.

A common use case is to render a component as direct child to document.body or some other DOM element that is not a direct parent of the component. This is useful for modals, tooltips, and other UI elements that need to escape the normal flow of the document.

Here we create a reusable reusable component Portal to render a child component into the document.body.

Show code
module Example.Portal

open Feliz
open Browser.Dom

[<ReactComponent>]
let Portal(content: ReactElement) =
ReactDOM.createPortal(content, document.body)

[<ReactComponent>]
let PortalsPopup() =
Html.div [
prop.style [
style.position.fixedRelativeToWindow
style.top 10
style.right 10
style.padding 10
style.backgroundColor.lightGreen
style.zIndex 1000
]
prop.children [
Html.p [
prop.text "Portals can be used to escape the parent component."
]
]
]

[<ReactComponent(true)>]
let PortalsContainer() =
let showBanner, setShowBanner = React.useState(true)
Html.div [
prop.style [
style.padding 10
style.overflow.hidden
]
prop.children [
Html.button [
prop.text "Toggle Popup"
prop.onClick (fun _ -> setShowBanner (not showBanner))
]
if showBanner then
Portal(PortalsPopup())
]
]