I'm trying to use Svelte with gridstack. But when I add my Svelte component in js it doesn't show up right. This adds a button, but the styling isn't working and the output isn't printed to the log.
<script>
import { onMount } from "svelte";
import Button from "./Button.svelte";
import GridStack from "gridstack/dist/gridstack.all.js";
import "gridstack/dist/gridstack.min.css";
onMount(() => {
var grid = GridStack.init();
grid.addWidget({ width: 2, content: "<p>Hello</p>" });
grid.addWidget({ width: 2, content: "<Button />" });
});
</script>
<style>
</style>
<div class='grid-stack'></div>
Full example: https://codesandbox.io/s/gallant-roentgen-jmnis?file=/App.svelte
As Rich mentioned in his comment, you cannot use a Svelte component inside a string that is interpreted as HTML by gridstack.js at runtime. In order for the Svelte compiler to do its magic, the component has to be part of the markup, not inside a string.
So for example, this would be how to add the button component below the gridstack container:
Now that we have the interactive
<Button />
, we just need to figure out how move it inside the grid stack.Luckily, the gridstack addWidget function can also accept a DOM node instead of an HTML string, so we can do something like this:
One way to achieve this is to use a Svelte action.
There is some extra logic (wrapping grid in a Promise and using
{#await ...}
) to make sure that the widget is not added before the grid has been initialized:A proper solution should probably also remove the element from the grid when it is removed from the DOM. According to the Svelte action documentation, this can be achieved by returning a
destroy()
method:A full demo of the solution is available here: https://codesandbox.io/s/mystifying-field-x2mkr?file=/App.svelte