Search code examples
sveltesapper

Hide other buttons on mouseover


I have a dynamic array of buttons and I want to hide others when one is hovered. There is a REPL here with my attempt.

It went well until I have to update a child prop from the parent. I get this error :

Props cannot be set directly on the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'

So I put the option line in my Btn.svelte but I still get an error. Am I missing something ? Or maybe there is an easier way ??

Thanks for your help !


Solution

  • There was another error, you didn't clear the isOpaque field when the button is actually hovered. Then, I suggest an optimization, the {#each} repeater emits the current index, so we don't need an extra variable for this. Here's my correction/suggestion using the $set method to update the component property:

    <script>
        import Btn from "./Btn.svelte";
        let current;
        const data = ["foo", "bar", "baz"];
        let btns = [];
    
        function overed (e) {
            console.log("overed :" + e.detail.data);
            btns.forEach((btn, i) => {
                btn.$set({isOpaque: e.detail.data !== data[i]})
            })
        }
    </script>
    
    <style>
    </style>
    
    {#each data as item, index}
    <Btn on:overed={overed} data={item} bind:this={btns[index]}>{item}</Btn>
    {/each}
    

    And here is a simplified version that does not require updating the child components property from the parent:

    https://svelte.dev/repl/f049fb762bfb481ca3c8998879a3cdb3?version=3.22.3