Loop over and render a list of data using an `each` block in Svelte 3

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years ago

Quite often we need to be able to loop over and render a list of data that (for example) is returned from the backend.

In this lesson we are going to learn how to use each block from Svelte to iterate over a list of data and render a list of European cities. We're also going to learn how to get the current index while iterating over a list, as well as how to destructure a currently iterated over element of the array.

Instructor: [0:00] We have a list of cities that we would like to render over here. To do that, create an each block. We're going to iterate over cities and as a city. Let me just go ahead and close the block, as well.

[0:12] Inside of this each block, we're going to render a list element with the city.name. This is going to render all the free cities that we have defined over here.

[0:23] If we would like to use the index, each block gets the index as its second argument. I can do index. I can go ahead and render the index like this. Index, save, refresh. We can see the index over here. Let me add plus one to the index. There you go.

[0:40] We don't have to use the city object because right now each city has an ID and a name. If you wanted to, we can destructure those properties from the city object like this. ID, name. Let me factor that. We're going to use ID equal ID, like this.

[0:59] If we decide to add another city, let me create a custom ID. We're going to have Lisbon. After I save this, it's going to be automatically applied because each block is going to iterate over all cities. We're going to render as many cities as we have in the cities array.

egghead
egghead
~ 6 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today