Svelte: Option to set slots when create component instance

Created on 27 Apr 2019  路  2Comments  路  Source: sveltejs/svelte

In svelte 2 it was possible to pass slots option when creating new component:

new Component({
      target: element,
      slots: { slot_name1: element1, slot_name2: element2, ... },
});

In svelte 3 slots options seems doesn't work. And there is no way to set slots after component instance is created.

This is needed to properly integrate svelte components that using slots into other frameworks.

slot proposal has pr

Most helpful comment

workaround with private apis is to do something like this:

import { detach, insert, noop } from 'svelte/internal';

function createSlots(slots) {
    const svelteSlots = {};

    for (const slotName in slots) {
        svelteSlots[slotName] = [createSlotFn(slots[slotName])];
    }

    function createSlotFn(element) {
        return function() {
            return {
                c: noop,

                m: function mount(target, anchor) {
                    insert(target, element, anchor);
                },

                d: function destroy(detaching) {
                    if (detaching) {
                        detach(element);
                    }
                },

                l: noop,
            };
        }
    }
    return svelteSlots;
}

new Component({
      target: element,
      props: {
          $$slots: createSlots({ slot_name1: element1, slot_name2: element2, ... }),
          $$scope: {},
     },
});

it seems works for me

All 2 comments

workaround with private apis is to do something like this:

import { detach, insert, noop } from 'svelte/internal';

function createSlots(slots) {
    const svelteSlots = {};

    for (const slotName in slots) {
        svelteSlots[slotName] = [createSlotFn(slots[slotName])];
    }

    function createSlotFn(element) {
        return function() {
            return {
                c: noop,

                m: function mount(target, anchor) {
                    insert(target, element, anchor);
                },

                d: function destroy(detaching) {
                    if (detaching) {
                        detach(element);
                    }
                },

                l: noop,
            };
        }
    }
    return svelteSlots;
}

new Component({
      target: element,
      props: {
          $$slots: createSlots({ slot_name1: element1, slot_name2: element2, ... }),
          $$scope: {},
     },
});

it seems works for me

@creaven thanks for this workaround. Saved me a headache converting a v2 modal component that relied on passing in slots to v3!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

AntoninBeaufort picture AntoninBeaufort  路  3Comments

plumpNation picture plumpNation  路  3Comments

ricardobeat picture ricardobeat  路  3Comments

Rich-Harris picture Rich-Harris  路  3Comments

sskyy picture sskyy  路  3Comments