1

Has anyone used Svelte in their projects? I just have a small question. Let's say you are looping through an array and displaying the data in the array. And there are 4 objects in the array. If I only want to style the first iteration (bluma). How do I do it?

let items = [
        { icon: 'book', title: 'bulma', tags: ['public', 'sources'] },
        { icon: 'book', title: 'marksheet', tags: ['private'] },
        { icon: 'book', title: 'minireset.css', tags: ['public', 'sources'] },
        { icon: 'code-branch', title: 'daniellowtw/infboard', tags: ['public', 'forks'] },
        { icon: 'code-branch', title: 'mojs', tags: ['private'] }
    ]

{#each filteredItems as item}
    <a class="panel-block {item.}">
    <span class="panel-icon">
            {#if item.icon === "code-branch"}
            <i class="fas fa-code-branch" aria-hidden="true"></i>
            {:else if item.icon ==="book"}
            <i class="fas fa-book" aria-hidden="true"></i>
            {/if}

2 Answers 2

4

Whenever a pure CSS approach is available, I would rather use that. Here you could make use of the :first-child selector:

<div class="panel-items">
{#each filteredItems as item}
    <a class="panel-block">
        <span class="panel-icon">
            {#if item.icon === "code-branch"}
                <i class="fas fa-code-branch" aria-hidden="true"></i>
            {:else if item.icon ==="book"}
                <i class="fas fa-book" aria-hidden="true"></i>
            {/if}
        </span>
    </a>
{/each}
</div>

<style>
    .panel-block {
        /* general panel block styling */
    }

    .panel-block:first-child {
        /* first panel block style overrides */
    }
</style>

Note that the entire loop is held within its own container div in order to make sure the first item in the loop is indeed the first child of its parent container.

Sign up to request clarification or add additional context in comments.

Comments

1

This can be done by using the index provided as a second argument of the #each block:

{#each filteredItems as item, i}
  <span style="color:{i === 0 ? 'green' : 'red'}">
    {item.title}
  </span>
{/each}

Reference: Each block in svelte tutorial.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.