How to get editor instance from another component in Svelte? #1289
Replies: 1 comment 2 replies
-
In Svelte, you can achieve similar functionality to Here's a basic example of how you might approach this:
// editorStore.js
import { writable } from 'svelte/store';
export const editor = writable(null);
// Editor.svelte
<script>
import { onMount } from 'svelte';
import { editor } from './editorStore';
import { Editor } from 'milkdown';
let editorInstance;
onMount(() => {
editor.set(editorInstance);
});
</script>
<Editor bind:this={editorInstance} />
// Tooltip.svelte
<script>
import { getContext } from 'svelte';
import { editor } from './editorStore';
const editorInstance = getContext('editor');
</script>
<!-- Use editorInstance as needed --> With this setup, the Tooltip component can access the Editor instance via context. Each instance of the Editor component will have its own Editor instance stored in the store, so they won't interfere with each other. This allows you to create multiple milkdown editors, each with its own instance. |
Beta Was this translation helpful? Give feedback.
-
In React and Vue, milkdown has the ability to get the editor instance from a provider.
In Svelte, however, I'm not able to retrieve the editor instance since there is no
useInstance
equivalent in Svelte.The problem is, the components are dynamically created like so:
There is no way to pass the editor as a prop in the above case.
Using
setContext
andgetContext
also doesn't work because the Tooltip component doesn't register as a child of the Editor component.Creating a store from a js/ts file and then using
get()
from the component does work, but the store is shared, because it's exported from a module. Therefore, I can't create multiple milkdown editors since they all share the same instance.Is there a way to retrieve the Editor instance from another component? Like a
useInstance
for Svelte?Beta Was this translation helpful? Give feedback.
All reactions