Properties, State, and Events
Learning objectives
- You rehearse the basics of Svelte components.
Here, we briefly summarize the key parts of Svelte components from the previous chapter.
Svelte Components
Each Svelte component consists of three optional parts: a script part, a template part, and a style part.
<script>
// JavaScript goes here
</script>
<!-- HTML template goes here -->
<style>
/* CSS goes here */
</style>
Component Properties
Component properties are declared in the script part of the component using the $props()
function. The function returns an object, which is decomposed to the explicit properties. The following example would have one property name
:
<script>
// JavaScript goes here
let { name } = $props();
</script>
<!-- HTML template goes here -->
<style>
/* CSS goes here */
</style>
Variables in HTML template
Variables are injected to the HTML template using curly brackets. The following example demonstrates the use of the name
variable (received as props) in the text.
<script>
// JavaScript goes here
let { name } = $props();
</script>
<!-- HTML template goes here -->
<p>My name is {name}.</p>
<style>
/* CSS goes here */
</style>
Curly brackets in the HTML template denote a JavaScript expression. Writing
{name}
evaluates the variablename
, which leads to{name}
being replaced with the value ofname
.
State and Reactivity
The function $state()
can be used to create a reactive state variable. The following example outlines the creation of a variable age
, which is given the initial value 0. The variable is then used in the HTML template. The variable is reactive, which means that changes to the variable is automatically reflected in the template.
<script>
// JavaScript goes here
let { name } = $props();
let age = $state(0);
</script>
<!-- HTML template goes here -->
<p>My name is {name}. I am {age} years old.</p>
<style>
/* CSS goes here */
</style>
Events and Event Handling
Events are handled in the HTML template with the on:eventname
syntax. The following example outlines the use of the on:click
event handler. The event handler is used to increment the age
variable by one.
<script>
// JavaScript goes here
let { name } = $props();
let age = $state(0);
</script>
<!-- HTML template goes here -->
<p>My name is {name}. I am {age} years old.</p>
<button on:click={() => age++}>Grow</button>
<style>
/* CSS goes here */
</style>
The event handler can be also implemented as a separate function. The following example outlines the use of the on:click
event handler with a separate function grow
.
<script>
// JavaScript goes here
let { name } = $props();
let age = $state(0);
const grow = () => {
age++;
};
</script>
<!-- HTML template goes here -->
<p>My name is {name}. I am {age} years old.</p>
<button on:click={grow}>Grow</button>
<style>
/* CSS goes here */
</style>