What is the Svelete components

Svelte components

Components are the mail parts of svelete. We need to use .svelete extension in the file name. Components contain three sections, script, markup and style.

	// logic goes here

<!-- markup (zero or more items) goes here -->

	/* styles go here */

1: Script:

Script tag contains javascript, it will run when component is initiated. We can define variables and access props on the top. To access the props we use “export”.

Export Props

export let varname = “abc”;

In the props we can set the initial value. If props not comes from the parent component then we can use the initial value.

We can also export class, function, const. It is readonly from the outside of the component.

Assignments are reactive

Svelte’s reactivity is triggered by assignments. We can not triggered reactivity by array push and splice method.

	let arr = [0, 1];

	function handleClick() {
		// this method call does not trigger an update
		// this assignment will trigger an update
		// if the markup references `arr`
		arr = arr;

Svelte script block run only when component is created. So assignment on the script block are not automatically run again when props are updated.

	export let person;
	// this will only set `name` on component creation
	// it will not update when `person` does
	let { name } = person;

$: marks a statement as reactive

We need to use $ to make a variable reactive. So when props value change then assigned variable also updated.

	export let title;
	export let person;

	// this will update `document.title` whenever
	// the `title` prop changes
	$: document.title = title;

	$: {
		console.log(`multiple statements can be combined`);
		console.log(`the current title is ${title}`);

	// this will update `name` when 'person' changes
	$: ({ name } = person);

	// don't do this. it will run before the previous line
	let name2 = name;

Prefix stores with $ to access their values

A store is an object that allows reactive access to a value. Using $ we can access the value from store in the any component.

	import { writable } from 'svelte/store';

	const count = writable(0);
	console.log($count); // logs 0

	console.log($count); // logs 1

	$count = 2;
	console.log($count); // logs 2

2: Style

Css inside the style tag it is scoped with the component. To apply styles to a selector globally, use the :global(...) modifier.

Leave a Comment

Your email address will not be published. Required fields are marked *