Creating Your First Svelte Component
Introduction to Svelte Components
Welcome to the second lesson of our course, "Svelte Basics: Getting Started and Core Concepts." In this lesson, we'll explore Svelte components, the fundamental building blocks of any Svelte application. Components encapsulate functionality, styles, and reactivity, making your code modular and reusable.
Our goal is to create a simple Svelte component and integrate it into your project, helping you understand how components work in practice. Let's get started!
Setting Up a Svelte Project
If you're working on your local machine, you need to set up a Svelte development environment. The easiest way to do this is by using Vite, a fast build tool optimized for modern front-end development. Run the following command in your terminal to create a new Svelte project:
During setup, select Svelte as the framework and proceed with the default options. Once the project is created, navigate to the directory and install dependencies:
This will start a local development server, allowing you to view your Svelte app in the browser.
Note: If you're working in the CodeSignal environment, you can skip this step. Everything you need is already installed, and you can start coding in Svelte right away! 🚀
Basic Structure of a Svelte Component
A Svelte component is typically structured into three main sections: <script>, HTML, and <style>. The <script> section is where you define your component's logic, such as variables and functions. The HTML section contains the markup that defines the component's structure, and the <style> section is where you apply styles to your component.
In Svelte, you can use TypeScript within the <script> tag to enhance your development experience with type safety. This is particularly useful for catching errors early and improving code readability. Remember, TypeScript is optional, but it can be a valuable tool as your projects grow in complexity.
Creating Your First Svelte Component
Let's create a simple Svelte component named MyComponent.svelte. In this component, we'll define a state variable using Svelte's runes, which is a new feature in Svelte 5 that replaces the traditional store mechanism. Here's how you can define a state variable:
In this example, we use the $state rune to create a reactive state variable name initialized with the value "World". The HTML section displays a greeting using this state variable, and the <style> section applies a blue color to the <h1> element. When you render this component, it will display "Hello, World!" in blue text.
Note: The
$staterune can only be used to define a variable, not to update it. Once a variable is declared using$state, you must modify its value directly without reassigning it. For example, instead ofcount = $state(0); count = $state(count + 1);, simply usecount = $state(0); count++;to update the state correctly.
