Search code examples
sveltesveltekitsvelte-3

Svelte render into div on exciting page dynamically using javasctipt function


I have a react app which I am checking the feasibility of moving to svelte

I do not render directly to page, I create package and the package has export method which helps who ever calling the API function.

eg: -

const render: Render = (containerId, options) => {
  const container = document.getElementById(containerId)
  ReactModal.setAppElement(container!)
  const root = createRoot(container!)
  root.render(
    <StrictMode>{options && <App options={options} />}</StrictMode>
  )
}

I want to achieve the same result with svelte, is it possible? I can't see any documentation anywhere to create a function that will render the svelte on the page.


Solution

  • You can render any Svelte component to a target of your choice using the constructor:

    new MySvelteComponent({
      target: element,
      props: {
      }
    })
    

    with target being an element, you could use querySelector to get the element. and props being the exported properties of the top most component.

    There are some other options, but you likely don't need them, you can find them in the docs.