Search code examples
sveltesvelte-3svelte-component

Svelte component inside another component and share props between


I want ask you how I can use Svelecte inside my component and forward all props and get all events to the parent.

My case:

App.Svelte

<script>
import Select from './Select.svelte';

const list = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2'}];
let myValue = null;
</script>

<h3>Select</h3>
<Select options={list} bind:value={myValue} label="Country"></Select>
<pre>{myValue}</pre>

Select.svelte

<script>
    import Svelecte from 'svelecte';

    export let label;
    let id = (Math.random() + 1).toString(36).substring(7);
</script>

<label for="{id}">{label}</label>
<Svelecte {...$$props} inputId={id}></Svelecte>

Binding in this case not working. Can you help me how I can use my own component including other component from other developer and forward props and get all events from there? I need selected item after select and get data to App.Svelte.

Thank you


Solution

  • I think if you pass on the props like {...$$props} you lose the binding. From the docs

    $$props references all props that are passed to a component, including ones that are not declared with export. It is not generally recommended, as it is difficult for Svelte to optimise. But it can be useful in rare cases – for example, when you don't know at compile time what props might be passed to a component.

    Simply export options and value and pass them declared and it seems to work REPL

    <script>
    import Select from './Select.svelte';
    
    const list = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2'}];
    let myValue = null;
    </script>
    
    <h3>Select</h3>
    <Select options={list} bind:value={myValue} label="Country"></Select>
    <pre>{myValue}</pre>
    
    Select.svelte
    <script>
        import Svelecte from 'svelecte';
    
        export let label, options, value
            
        let id = (Math.random() + 1).toString(36).substring(7);
    </script>
    
    <label for="{id}">{label}</label>
    <Svelecte {options} bind:value inputId={id}></Svelecte>