Jed
Jed

Reputation: 703

Svelte component attribute dynamic value

See example here: https://svelte.dev/repl/7fd322d6b7d641359774de781f013f45?version=3.18.1

I'm trying to make the value of a component's property dynamic, by checking if that component's id matches the selected id:

App.svelte

<script>
    import BanjoPlayer from './BanjoPlayer.svelte'
    let banjoPlayers = [{id: 1, name:'Scruggs'},{id: 2, name:'Pickelny'}]
    let selectedBP = 0
</script>
<ul>
{#each banjoPlayers as bp (bp.id)}
    <BanjoPlayer on:click="{e => selectedBP = bp.id}" {...bp} selected="{selectedBP === bp.id}" />
{/each} 
</ul>

BanjorPlayer.svelte

export let name
export let id
export let selected
</script>

<li on:click class:selected >
    {name} ({id})
</li>

I've included two other attempts in the REPL: an alternative that I thought might work (but doesn't) and an alternative that works but is certainly not ideal.

Upvotes: 1

Views: 1779

Answers (1)

rixo
rixo

Reputation: 25001

It's a bug, it should work, as far as I can tell.

It has to do with the spread {...bp} apparently.

Equivalent code without the spread works as expected:

<script>
    import BanjoPlayer from './BanjoPlayer.svelte'
    let banjoPlayers = [{id: 1, name:'Scruggs'},{id: 2, name:'Pickelny'}]
    let selectedBP = 0

    function isSelected(id) {
        console.log(id);
        return selectedBP === id
    }
</script>

<h2>
    The selcted player id is: {selectedBP}
</h2>

<p>
<em>How I want it to work:</em>
</p>
<ul>
{#each banjoPlayers as bp (bp.id)}
    <BanjoPlayer on:click="{e => selectedBP = bp.id}" selected="{selectedBP === bp.id}" id={bp.id} name={bp.name} />
{/each} 
</ul>

REPL

Upvotes: 3

Related Questions