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

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.