Opens an external site in a new window
Pray for peace.
RODNEY LAB
  • Home
  • Plus +
  • Projects
  • Giving
  • Contact
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Contact

Using Svelte Each Blocks: Const Directives & Destructuring # Using Svelte Each Blocks: Const Directives & Destructuring #

Using Svelte Each Blocks
  1. Rodney Lab Home
  2. Rodney Lab Blog Posts
  3. SvelteKit Blog Posts
<PREVIOUS POST
NEXT POST >
LATEST POST >>

Using Svelte Each Blocks: Const Directives & Destructuring #

Published: 11 months ago
4 minute read Gunning Fog Index: 6.6
Content by Rodney
Author Image: Rodney from Rodney Lab
SHARE:

👨‍👨‍👧‍👧 Using Svelte #each Blocks #

This post on using Svelte each blocks will be helpful not only if you are new to Svelte and you are seeing each blocks for the first time. The video is also worth a watch if you are already comfortable with them. That is because as well as running through how each blocks work in Svelte, we will sprinkle in a few new Svelte features. Even experts might not yet have seen these in the wild!

You use Svelte each blocks to cycle through arrays and array-like objects. For example, in our code we have an array of RGB colours and display them to the browser, one-by-one. On top we make use of destructuring and Svelte const directives within the each block to simplify the code. If you are new to Svelte, it would be well worth cloning the app and adding extra features to cement your understanding. Anyway take a look at the video and do let me know how you use the code. If you are a Svelte pro also let me know how you optimise the code even further.

Also look out for the guest appearance by Svelte style directives! You can drop a comment below or reach out for a chat on Element  as well as Twitter @mention  if you have suggestions for improvements or questions.

📹 Using Svelte Each Blocks: Video #

Please enable JavaScript to watch the video 📼

Using Svelte Each Blocks: Const Directives & Destructuring

🗳 Poll #

What will you use to create you next Svelte site?
Voting reveals latest results.

🖥 Using Svelte Each Blocks: Code #

Final version of #each block #

src/routes/+page.svelte
svelte
    
<script>
let colours = [
{ red: 0, green: 5, blue: 1 },
{ red: 247, green: 244, blue: 243 },
{ red: 255, green: 159, blue: 28 },
{ red: 48, green: 131, blue: 220 },
{ red: 186, green: 27, blue: 29 },
];
let colourCount = colours.length;
let colourSystem = 'hex';
// ...TRUNCATED see full version in GitHub repo (link below)
</script>
{#each colours as { red, green, blue }, index}
{@const hex = rgbToHex({ red, green, blue })}
{@const hsl = rgbToHsl({ red, green, blue })}
{@const colourClass = textColourClass({ red, green, blue })}
<article
style:background-color={hex}
aria-posinset={index + 1}
aria-setsize={colourCount}
class={`colour ${colourClass}`}
>
{#await colourName(hex)}
...
{:then name}
{`${name}: `}
{/await}
<span class="colour-code">
{#if colourSystem === 'hex'}
{hex}
{:else if colourSystem === 'rgb'}
rgb({red} {green} {blue})
{:else}
{hsl}
{/if}</span
>
</article>
{/each}

🦄 Want more? #

For a more complete introduction to Svelte, try the Starting out Svelte and SvelteKit tutorial  where we build out the app in this video. We add extra features like checking contrast ratio and generating tints and shades as well as a form for adding new colours. While doing all that we learn other Svelte features.

🔗 Using Svelte Each Blocks: Links #

  • Video on using fetch in SvelteKit and await blocks,
  • Rodney Lab GitHub repo with full code  ,
  • the Colour API used in the video  ,
  • Twitter handle: @askRodney  .

🏁 Using Svelte Each Blocks: Summary #

How do you loop or iterate over an array in Svelte? #

Each blocks are helpful for looping, or iterating, over arrays and array-like objects in Svelte. They are a Svelte language feature so not unique to SvelteKit. On top the syntax is quite simple. The block's first line is wrapped in braces and starts #each: '{#each arrayName as elementName}'. You can then use elementName to access the current element of the input array within the block. Close the block with {/each}. If you need access to the index in the loop, add an extra variable to hold this. We have seen you can do this neatly, separating the two identifiers with a comma.

Can you declare variables in a Svelte each block? #

For convenience Svelte has an @const directive for declaring local variables within an each block. This can simplify code, making it easier to read. You might use this to store an intermediate or calculated value, especially if that value is used several times inside the each block.

Can you destructure array elements in a Svelte each block? #

We have seen destructuring works in Svelte each blocks and is another way to simplify your code. As well as destructuring, you can rename array element object fields. This can be handy if you want to add shortcut object syntax within your each block; change incoming object field names to match those in existing objects for cleaner code.

🙏🏽 Feedback #

If you have found this video useful, see links below for further related content on this site. I do hope you learned one new thing from the video. Let me know if there are any ways I can improve on it. I hope you will use the code or starter in your own projects. Be sure to share your work on Twitter, giving me a mention so I can see what you did. Finally be sure to let me know ideas for other short videos you would like to see. Read on to find ways to get in touch, further below. If you have found this post useful, even though you can only afford even a tiny contribution, please consider supporting me through Buy me a Coffee.

@askRodney avatar

Rodney

@askRodney

Just dropped a video talking you through

#each blocks in Svelte:

- nice introduction to each in ❤️ Svelte if you are learning Svelte,

- level up on const directives and destructuring if you haven't yet used latest features.

Hope you find it useful!https://t.co/KfdkY5tOv2

— Rodney (@askRodney) March 28, 2022

Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram  . Also, see further ways to get in touch with Rodney Lab. I post regularly on SvelteKit as well as Search Engine Optimisation among other topics. Also subscribe to the newsletter to keep up-to-date with our latest projects.

Thanks for reading this post. I hope you found it valuable. Please get in touch with your feedback and suggestions for posts you would like to see. Read more about me …

Rodney from Rodney Lab
TAGS:
SVELTEKIT

Likes:

Likes

  • Ryan Arpe profile avatar
Likes provided by Twitter via Webmentions.

Related Post

Starting out Svelte and SvelteKit: Beginners’ Tutorial

Starting out Svelte and SvelteKit: Beginners’ Tutorial

plus
sveltekit
<PREVIOUS POST
NEXT POST >
LATEST POST >>

Leave a comment …

Your information will be handled in line with our Privacy Policy .

Ask for more

1 Nov 2022 — Astro Server-Side Rendering: Edge Search Site
3 Oct 2022 — Svelte eCommerce Site: SvelteKit Snipcart Storefront
1 Sept 2022 — Get Started with SvelteKit Headless WordPress

Copyright © 2020 – 2023 Rodney Johnson. All Rights Reserved. Please read important copyright and intellectual property information.

  • Home
  • Plus +
  • Newsletter
  • Contact
  • Terms of Use
  • Privacy Policy
We use cookies  to enhance visitors’ experience. Please click the “Options” button to make your choice.  Learn more here.