node.jsarrayssveltesveltekitsvelte-component

How do I pass props in each blocks in Ssvelte


I'm a bit confused with Svelte's props. I have a component named Assignment which I will use in my Board component. I wish to have a dynamic array prop in my Assignment's {#each} block.

<script>
    export let array
</script>

<div {array} class="flex-column">
    <div class="row-item">
        <h4>Open</h4>
        {#each {array} as value}
            <div class="description">
                <p>{value.status}</p>
                <p>{value.name}</p>
            </div>
        {/each}
    </div>
</div>

Above is my Assignment component

My wish is for me to able to do something like this:

<div class="flex-container">
    <Assignment
        {myArray}
    />
    <Assignment
        {myArray2}
    />
</div>

With a new array in each component call. So I guess my question is: How do I pass a prop into a each block?


Solution

  • When using an {#each ...} block, you don't use braces around the value to iterate over; just {#each array as value} will do:

    <script>
        export let array;
    </script>
    
    <div class="flex-column">
        <div class="row-item">
            <h4>Open</h4>
            {#each array as value}
                <div class="description">
                    <p>{value.status}</p>
                    <p>{value.name}</p>
                </div>
            {/each}
        </div>
    </div>
    

    In addition, you do not need to add an array property to your div element. <div {array}> is a shorthand property and is equivalent to <div array={array}>. array isn't a valid attribute for a regular div element, but Svelte doesn't know or care about that and will happily apply the array attribute to a div. Its value is just the string representation of an array of objects ([object Object],[object Object] as you can see in your screenshot). However, that's not actually doing anything in this case; the {#each ...} doesn't see that as a variable and just uses the component's variable anyways, so it can be removed.


    Then in your Board component, you can declare the Assignment component multiple times with different array properties, but when declaring the property, you need the property name, as in <Assignment array={myArray} />:

    <script>
        import Assignment from './Assignment.svelte';
        
        let myArray = [{
            status: 'status 1',
            name: 'name 1',
        }];
        
        let myArray2 = [{
            status: 'status 2',
            name: 'name 2',
        }];
    </script>
    
    <div class="flex-container">
        <Assignment
            array={myArray}
        />
        <Assignment
            array={myArray2}
        />
    </div>
    

    Further reading: