Svelte Each Block/onMount Example

If you’re looking for an alternative to React, Vue, Angular, Mithril or BackboneJS, Svelte comes first as an extremely straight forward JScript framework. There is no virtual dom in Svelte and also it’s pretty fast to work with it.

Here is a simple example to show you how fun to work with Svelte.

You can get Svelte with the following command.

npx degit sveltejs/template my-svelte-project

If you get an error like me, download this zip file and extract it in a folder. Next cd in to folder and install required packages with the following command.

npm install

And run…

npm run dev

Svelte means less code. I will show you how.

Now… edit App.svelte

<script>
import Posts from './Posts.svelte';
import { onMount } from 'svelte';

let data = [];

onMount(async () => {
let response = await fetch('https://jsonplaceholder.typicode.com/posts');
data = await response.json();
});

</script>

<Posts data={data}/>

This example is fetching sample json data and passing it to Posts.svelte to list it.

Create a file called Posts.svelte

<script>
export let data;
</script>

{#each data as item}
<h1>{item.title}</h1>
<p>{item.body}</p>
{/each}

You should see how easy it is. I will post more examples soon.