2020-04-21

Svelte Tutorial 3: Component Properties (English & Indonesia)

English


Props or properties used when we want to pass data or value from one component to its children.

Declaring props


To declare props we need to use keyword export. For example when we have app like this:

<script>
import Nested from './Nested.svelte';
</script>

<Nested answer={42}/>  <!-- undefined if we forget keyword 
                            'export' when declaring answer -->

We need to declare answer with export keyword in Nested.svelte, otherwise answer will be considered undefined in the app

<script>
export let answer;
</script>

<p>The answer is {answer}</p>

Default value


We can also specify default value of answer from previous example like this:

<script>
export let answer = 'default';
</script>

So if we have something like this:

<Nested answer={42}/>  <!-- will print 42 -->
<Nested/>              <!-- will print default -->

Spread props


Assuming you have Info.svelte component which have 4 props (nameversionspeedwebsite),

<script>
export let name;
export let version;
export let speed;
export let website;
</script>
<p>
The <code>{name}</code> package is {speed} fast.
Download version {version} from <a href="https://www.npmjs.com/package/{name}">npm</a>
and <a href={website}>learn more here</a>
</p>

you can assign value like this:

<script>
import Info from './Info.svelte';

const pkg = {
name: 'svelte',
version: 3,
speed: 'blazing',
website: 'https://svelte.dev'
};
</script>

<Info name={pkg.name} version={pkg.version} speed={pkg.speed} website={pkg.website}/>

But instead of specifying one by one, you can also spread value like this, note that index name must be the same with the component.

<Info {...pkg}/>





Indonesia


Property adalah sesuatu yang digunakan untuk memberikan data atau nilai dari suatu komponen ke level komponen di bawahnya (child).

Declaring props


Untuk mendeklarasikan property kita bisa menggunakan keyword export. Sebagai contoh jika kita mempunyai app seperti ini:

<script>
import Nested from './Nested.svelte';
</script>

<Nested answer={42}/>  <!-- undefined jika kita lupa keyword 
                            'export' saat deklarasi answer -->

Kita harus mendeklarasikan answer dengan keyword export di dalam Nested.svelte, jika tidak maka answer tidak akan dikenali di app utama.

<script>
export let answer;
</script>

<p>The answer is {answer}</p>

Default value


Kita juga bisa memberikan nilai default pada variable answer dari contoh sebelumnya:

<script>
export let answer = 'default';
</script>

Jadi jika kita memanggil nested seperti ini:

<Nested answer={42}/>  <!-- akan mencetak 42 -->
<Nested/>              <!-- akan mencetak 'default' --> 


Spread props


Misalkan kita mempunyai komponen Info.svelte yang memiliki 4 properti (nameversionspeedwebsite)

<script>
export let name;
export let version;
export let speed;
export let website;
</script>
<p>
The <code>{name}</code> package is {speed} fast.
Download version {version} from <a href="https://www.npmjs.com/package/{name}">npm</a>
and <a href={website}>learn more here</a>
</p>

kita bisa memasukkan nilai variabel seperti ini:

<script>
import Info from './Info.svelte';

const pkg = {
name: 'svelte',
version: 3,
speed: 'blazing',
website: 'https://svelte.dev'
};
</script>

<Info name={pkg.name} version={pkg.version} speed={pkg.speed} website={pkg.website}/>

Akan tetapi daripada memasukan satu-satu, kita juga bisa langsung memasukkan variabel seperti contoh di bawah ini. Tapi satu hal yang perlu diperhatikan nama indeks pkg yang digunakan harus sama dengan di Info.svelte yaitu (nameversionspeedwebsite)

<Info {...pkg}/>


2020-04-10

Svelte Tutorial 2: Reactivity (English & Indonesia)

English


Reactivity is the ability of the system in svelte to keep DOM in sync with application state. Svelte automatically update DOM/invalidate state if there's an assignment operator. Below is explanation of reactivity in Svelte:

Assignment


For example when you have function handleClick like this:

<script>
 let count = 0;

 function handleClick() {
  count += 1;
 }
</script>

<button on:click={handleClick}>
   Clicked {count} {count === 1 ? 'time' : 'times'}
</button>


that is called everytime there is a click on the button, when handleClick assign new value to variable count the text on the button get updated automatically, so it will represent new value of count.

Declaration


When you want to have variable that respond to change of state happen within your app, use reactive declaration like this:

<script>
 let count = 0;
 $: doubled = count * 2;      // reactive declaration
 function handleClick() {

  count += 1;
 }

</script>

<button on:click={handleClick}>
 Clicked {count} {count === 1 ? 'time' : 'times'}
</button>

<p>{count} doubled is {doubled}</p>


Notice the $: sign before declaring doubled, so when count variable gets updated doubled also changed to represent new value.

Statement


You can also use reactive declaration for any statement, for example, we can log the value of count whenever it changes:

$: console.log(`the count is ${count}`);

you can also grouped several statement together:

$: {
 console.log(`the count is ${count}`);
 alert(`I SAID THE COUNT IS ${count}`);
}


you can even use reactivity for if statement:

<script>
 let count = 0;
 $: if (count >= 10) {
  alert(`count is dangerously high!`);
  count = 9;
 }
 function handleClick() {
  count += 1;
 }
</script>
<button on:click={handleClick}>
 Clicked {count} {count === 1 ? 'time' : 'times'}
</button>


Notice the $: sign before every statement or block of statement, if you are not using this, then your statement wont be reactive and wont be executed as the value of variable changed.

Updating array or object


Because in svelte reactivity is triggered by assignment, if you use array method like push, new state wont be updated. So you will have to add another line that seem redundant but since it does assignment, it will trigger reactivity

numbers.push(numbers.length + 1);  // no assignment = not reactive
numbers = numbers                  // has assignment = reactive


you can also use something like this  (will be reactive)

numbers = [...numbers, numbers.length + 1];

Assignments to properties of arrays and objects — e.g.
obj.foo += 1 or array[i] = x , work the same way as assignments to the values themselves (will be reactive). A simple rule of thumb: the name of the updated variable must appear on the left hand side of the assignment. This example below won't update references to obj.foo.bar, unless you follow it up with obj = obj.

const foo = obj.foo;
foo.bar = 'baz';







Indonesia


Reactivity adalah kemampuan sistem svelte untuk mejaga DOM tetap sama dengan keadaan aplikasi. Svelte akan meng update DOM/invalidate state secara otomatis apabila ada operasi perubahan/pengisian nilai ke dalam variabel menggunakan operator assignment (=). Berikut di bawah ini adalah penjelasan reactivity dalam svelte:

Assignment


Sebagai contoh ketika kita mempunyai fungsi handleClick seperti ini:

<script>
 let count = 0;

 function handleClick() {
  count += 1;
 }
</script>

<button on:click={handleClick}>
   Clicked {count} {count === 1 ? 'time' : 'times'}
</button>


yang akan dipanggil setiap kali ada klik pada button, maka ketika handleClick mengisi  nilai yang baru ke variable count, tulisan pada tombol akan terupdate secara otomatis, menyesuaikan dengan nilai yang baru count.

Declaration


Ketika kita ingin mempunya variabel yang merespon perubahan nilai yang terjadi di aplikasi, gunakan deklarasi reactive seperti ini:

<script>
 let count = 0;
 $: doubled = count * 2;      // deklarasi reactive
 function handleClick() {

  count += 1;
 }

</script>

<button on:click={handleClick}>
 Clicked {count} {count === 1 ? 'time' : 'times'}
</button>

<p>{count} doubled is {doubled}</p>


Perhatikan tanda $: sebelum deklarasi variabel doubled, maka ketika variabel count dirubah nilainya, variabel doubled juga akan berubah menyesuaikan dengan nilai baru yang semestinya.

Statement


Kita juga bisa menggunakan deklarasi reactive untuk kalimat apapun, sebagai contoh, kita bisa memasukkan perubahan nilai count ke dalam log:

$: console.log(`the count is ${count}`);

bisa juga mengelompokkan beberapa baris:

$: {
 console.log(`the count is ${count}`);
 alert(`I SAID THE COUNT IS ${count}`);
}


bahkan bisa digunakan untuk kalimat if

<script>
 let count = 0;
 $: if (count >= 10) {
  alert(`count is dangerously high!`);
  count = 9;
 }
 function handleClick() {
  count += 1;
 }
</script>
<button on:click={handleClick}>
 Clicked {count} {count === 1 ? 'time' : 'times'}
</button>


Perhatikan tanda $: sebelum semua kalimat atau kelompok kalimat, jika lupa menambahkan tanda ini maka kalimat itu tidak akan reactive dan tidak akan dieksekusi biarpun ada perubahan nilai pada variabel.

Updating array or object


Karena di svelte reactivity dipicu oleh assignment (tanda =) , jika kita menggunakan method array seperti push, maka reactivity tidak akan berjalan. Maka untuk memancing supaya reactive, kita bisa menambahkan baris (yang terlihat redundant) seperti di bawah ini:

numbers.push(numbers.length + 1);  // no assignment = not reactive
numbers = numbers                  // has assignment = reactive


Kita juga bisa menggunakan penambahan array seperti di bawah ini (akan reactive):

numbers = [...numbers, numbers.length + 1];

Assignment pada properti objek atau array — seperti ini:
obj.foo += 1 atau array[i] = x , akan menghasilkan sesuatu yang sama dengan jika melakukan assignment pada nilai variabel langsung (jadi akan reactive). Aturan sederhana yang bisa kita pegang adalah jika nama dari variabel yang diubah nilai nya ada di sebelah kiri operator assignment (tanda =) maka akan memicu reactivity.
Contoh di bawah ini tidak akan mengubah nilai pada obj.foo.bar, karena obj.foo ada di sebelah kanan, kecuali kita menambahkan obj = obj untuk memancing reactivity

const foo = obj.foo;
foo.bar = 'baz';


Svelte Tutorial 1: Introduction to Svelte (English & Indonesia)

English


Svelte is a tool for building fast web applications. It's a competitor to React, Vue, Ember, Aurelia, and Angular, but it's better since it was compiled/errors checked at compile time before combined into a bundle.js file, not needing any virtual DOM/different template file/language like JSX, also because Svelte has the lowest learning curve among all. To learn more why Svelte is better than the rest, see Rich Harris' presentation about Rethinking Reactivity. To create a new svelte project use this command after you installed nodejs, npm, and npx:

npx degit sveltejs/template project1
cd project1
npm install # install dependencies
npm run dev


You can look at the result in the browser, and edit that project directly side by side (it has live reload). In Svelte, an application is composed from one or more components. A component is a reusable self-contained block of code that encapsulates HTML, CSS and JavaScript that belong together, written into a .svelte file. Here are some basics in svelte:

How to declare and use variable


First, add a <script> tag to your component and declare a variable (name)

<script>
let name = 'world';
</script>

Then, we can refer to variable in the markup using curly braces.

<h1>Hello {name}!</h1>

We can also use curly braces to put any JS we want.

How to create dynamic attributes:


We can use variable to create dynamic attributes:

<script>
let src = 'tutorial/image.gif';
</script>
<img src={src}>

We can use variable to specify image source, so we can dynamically determine link source programmatically for example.

You can also use shorthand feature when variable name and attribute is the same, like this:

<img {src}>

Styling


Just like in HTML, you can add a <style> tag to your component:

<style>
p {
color: purple;
font-family: 'Comic Sans MS', cursive;
font-size: 2em;
}
</style>


<p>This is a paragraph.</p>

What is special in svelte is style is scoped within component so when you set <p> style in one component, it wont accidentally change <p> style elsewhere within your app.

Nested component


It would be impractical to put your entire app in a single component. Instead, we can import components from other files and include them as though we were including elements.

For example we can have file Nested.svelte like this:

<p>This is another paragraph.</p>

Then we can use Nested component by importing it like this:

<script>
import Nested from './Nested.svelte';
</script>

Nested in this case can be anything, and totally independent to the file name (So you can name it anything, but it's a good practice to import with same name as the file name). And when we want to use it, just use it like you would when using predefined tags

<p>This is a paragraph.</p> <!-- normal predefined tag -->

<Nested/>                   <!-- your made up tag -->

Notice that even though both  <p> and <Nested> actually used same  <p> tag, but each style is independent as now its considered different component. One more thing to remember, tag name is case sensitive, so <Nested> not the same with <nested>

Unescaping HTML tags


Ordinarily, strings are inserted as plain text, meaning that characters like < and > have no special meaning. But sometimes you need to render HTML directly into a component. For example, the words you're reading right now exist in a markdown file that gets included on this page as a blob of HTML.

<script>
let str = `string contains <strong>HTML!!!</strong>`;
</script>

So instead of doing this:

<p>{str}</p>

In Svelte, you can do this with the special {@html ...} tag:

<p>{@html str}</p>



Indonesia


Svelte adalah alat untuk membuat web application secara cepat. Svelte adalah pesaing dari ReactVueEmberAurelia, and Angular, tapi svelte kami nilai lebih baik karena dicompile dan dicek error nya saat compile, baru kemudian digabungkan dalam file bundle.js, dan tidak membutuhkan virtual DOM atau file/bahasa template yang berbeda seperti JSX, svelte juga termasuk yang paling mudah dipelajari dibanding yang lainnya. Untuk lebih meyakinkan kenapa Svelte lebih baik dari yang lain, kamu bisa tonton persentasi Rich Harris tentang Rethinking Reactivity. Untuk membuat project Svelte yang baru gunakan perintah ini sesudah kamu menginstall nodejs, npm, dan npx:

npx degit sveltejs/template project1
cd project1
npm install # install dependencies
npm run dev


Kamu bisa melihat hasil web mu di browser, dan meng edit project itu langsung secara berdampingan (Svelte punya live reload). Di dalam svelte aplikasi dibentuk dari satu atau lebih komponen. sebuah komponen adalah blok program yang berdiri sendiri dan bisa digunakan berulang kali, yang terdiri atas HTML, CSS dan Javascript yang saling berhubungan, dikumpulkan menjadi satu dalam file .svelte. Berikut adalah dasar-dasar dalam Svelte:

Cara mendeklarasi dan menggunakan variabel

Pertama, tambahkan tag <script> dan deklarasikan variabel (name)

<script>
let name = 'world';
</script>

Kemudian kita bisa menggunakan variabel di dalam markup menggunakan kurung kurawal.

<h1>Hello {name}!</h1>

Kita juga bisa menggunakan kurung kurawal untuk memasukkan program JS.

Cara membuat atribut yang dinamis


Kita bisa menggunakan variabel untuk membuat atribut yang dinamis:

<script>
let src = 'tutorial/image.gif';
</script>
<img src={src}>

Karena kita bisa menggunakan variabel untuk memasukkan alamat asal image, maka kita bisa mengatur alamatnya secara dinamis dalam pemrograman.

Kita juga bisa menggunakan cara singkat jika nama variabel dan nama atributnya sama, seperti ini:

<img {src}>

Styling


Sama persis seperti di HTML, kamu juga bisa menambahkan tag  <style> ke komponen yang kamu buat.

<style>
p {
color: purple;
font-family: 'Comic Sans MS', cursive;
font-size: 2em;
}
</style>

<p>This is a paragraph.</p>

Yang istimewa dari svelte adalah style yang kamu tambahkan akan dibatasi hanya di dalam komponen tersebut, jadi misal dalam contoh di atas, style warna ungu tidak akan merubah style <p> lainnya dalam aplikasi buatanmu.

Nested component


Untuk tujuan pembuatan aplikasi yang baik, alangkah baiknya apabila kita tidak memasukkan smua app kita dalam satu komponen saja, melainkan bisa dipecah-pecah menjadi beberapa komponen kecil yang bisa digunakan berulang kali apabila dibutuhkan di kemudian hari. Kita bisa import komponen yang sudah dibuat tadi dari file lain dan di include kan seperti jika kita meng include kan elemen.

Sebagai contoh jika kita mempunya file Nested.svelte yang isinya seperti ini:

<p>This is another paragraph.</p>

Maka kita bisa memasukkan komponen Nested dengan cara import seperti ini:

<script>
import Nested from './Nested.svelte';
</script>

Nama elemen Nested bisa saja dirubah dengan nama lain, jadi nama ini tidak berhubungan dengan nama file nya (tapi akan jadi kebiasaan yang lebih baik jika dinamakan sama saja dengan nama file nya, supaya tidak bingung sendiri begitu maksudnya). Kemudian jika mau menggunakan tinggal gunakan dengan cara yang sama seperti menggunakan tag HTML pada umumnya.

<p>This is a paragraph.</p> <!-- html normal -->

<Nested/>                   <!-- tag buatan sendiri -->

Perhatikan meskipun kedua <p> dan <Nested> sebenarnya sama2 menggunakan tag <p>, tapi style masing2 tidak akan saling mempengaruhi, karena sekarang mereka sudah dianggap sebagai komponen yang berbeda. Satu lagi yang harus diingat, nama komponen buatanmu sifatnya case sensitive, jadi <Nested>  tidak sama dengan <nested>

Unescaping tag HTML


Biasanya, string akan dianggap sebagai plain text, jadi jika di dalam string itu ada karakter seperti   < dan > maka tidak akan dianggap sebagai sesuatu yang istimewa. Tapi kadang kita memang ingin menganggapnya sebagai HTML dan memasukkan langsung ke dalam komponen. Sebagai contoh kata-kata yang dimasukkan mengandung tag <strong>, supaya tulisan jadi bold.

<script>
let str = `string contains <strong>HTML!!!</strong>`;
</script>

Maka daripada memasukkan variabel seperti biasa dengan kurung kurawal:

<p>{str}</p>

Di svelte kita bisa melakukan dengan tag {@html ...} seperti ini, maka tulisan akan mengandung bold di bagian yang ada tag <strong>:

<p>{@html str}</p>