[React] Is there a way to use React Portals?

The function I suppose I should use is:

createPortal(
    children: ReactNode?,
    container: Element,
    key: Key? = definedExternally,
)

What I tried is doing something like this:

A component (Modal.kt)

val Modal = FC<Props> {
    p {
        +"A model modal"
    }
}

Then in the main App component:

val App = FC<Props> {
    val modalContainer = document.getElementById("menu-root") ?: error("Couldn't find menu root container!")
   createPortal(Modal.create(), modalContainer)
}

And in the main method:

fun main() {
    val container = document.getElementById("root") ?: error("Couldn't find root container!")
    createRoot(container).render(App.create())
}

This doesn’t work however. I’ve tried writing something akin do what you’d write in vanilla React:

In Modal.kt

val modalContainer = document.getElementById("modal-root") ?: error("Couldn't find modal root!")
val modalComponent = FC<Props> {
    p {
        +"A model modal"
    }
}

val Modal = createPortal(
    modalComponent.create(),
    modalContainer
)

And in the main App component:

val App = FC<Props> {
    +Modal // Is of type ReactPortal, so you can't invoke it like a function
}

This doesn’t work, however, so I feel pretty stuck. Would anybody be able to provide insight into this? It would be greatly appreciated!

1 Like