Search code examples
sveltesvelte-3

Svelte #each Style


I am using the each block similar to the code below. I have an array of items that is iterated through and then a button is create for all of the items.

<ul>
    {#each cats as { id, name }, i}
        <li><button target="_blank" href="https://www.youtube.com/watch?v={id}">
            {i + 1}: {name}
        </button></li>
    {/each}
</ul>

But I would like to stylize the buttons uniquely. For example I want the first button to be red and square, the next to be yellow and round, and the last normal. How would I go about adding that to the example above?


Solution

  • There are a couple ways I can see doing this:

    Use the nth-child() selector to style each button differently:

    li:nth-child(1) > button { color: red; }
    li:nth-child(2) > button { color: green; }
    

    Add a different class from an array based on the index

    <script>
      const classes = ['green', 'red', 'yellow']
    </script>
    {#each item as item, i}
      <li class={classes[i]}>...</li>
    {/each}
    

    (here you could use the modulo operator if you want the classes to repeat)

    A last way is to retrieve the classes from a function (this is very similar to the first one but can be more flexible)

    <script>
      function getClasses(index) {
        return 'something here';
      }
    </script>
    {#each item as item, i}
      <li class={getClasses(i)}>...</li>
    {/each}
    

    If you don't want to use classes you can of course do a similar thing with styles instead

    <script>
      function getStyle(index) {
        return 'something here';
      }
    </script>
    {#each item as item, i}
      <li style={getStyle(i)}>...</li>
    {/each}