DEV Community

Rafael Abuawad
Rafael Abuawad

Posted on

Svelte for Beginners: A Beginner's Guide to Building Web Applications

Svelte is a popular JavaScript framework for building web applications. Thanks to some tricks it is lightweight and easy to use, making it a great option for beginners. In this blog post, we'll take a look at how to set up Svelte and give code samples for working with forms, reactive states, and stores.

Setting up Svelte

To get started, you'll need to have Node.js installed on your machine. Once you have Node.js installed, you can use Vite to create a new Svelte project:

npm create vite@latest my-svelte-app -- --template svelte
Enter fullscreen mode Exit fullscreen mode

This will create a new directory called my-svelte-app and initialize it with the Svelte template. Next, navigate to the new directory and install the necessary dependencies:

cd my-svelte-app
npm install
Enter fullscreen mode Exit fullscreen mode

Now that you have your project set up, you can start the development server using the following command:

npm run dev
Enter fullscreen mode Exit fullscreen mode

This will start a development server and open your project in a web browser. You should see a "Vite + Svelte" message on the page, on top of a count button, if you press that button you will see how the count increases, we will learn how to do that ourselves in the following section.

Open that directory on a code editor of your choice, you can see an App.svelte file inside the src folder, remove all of its contents. Also delete the src/lib folder, we will not use it in this case.

Working with Reactive State

Svelte uses a reactive system to automatically update the DOM when the state of a component changes. In the following example, we'll create a simple counter that increments and decreases a value when clicking buttons.

Open the App.svelte file, and type the following:


<script>
  let count = 0;

  function increment() {
    count += 1;
  }

  function decrement() {
    count -= 1;
  }
</script>

<button on:click={decrement}>-</button>
<span>{count}</span>
<button on:click={increment}>+</button>

Enter fullscreen mode Exit fullscreen mode

In this example, we created two buttons, one to increment the count and one to decrease the count. The on:click directive is used to attach click events to the buttons, which call the increment and decrement functions respectively. The count variable is used to store the current value of the counter, which is displayed in a span element using curly braces ({}).

When the increment or decrement function is called, the value of the count variable is updated, and Svelte's reactive system automatically updates the span element to reflect the new value.

Working with forms

Svelte makes it easy to work with forms and inputs. In the following example, we'll create a simple form with text input and a submit button. The form will have a submit event that will output the text input's value to the console when the button is clicked.

Remove all of the contents on App.svelte, and write:


<script>
  let name = "";

  function handleSubmit() {
    console.log(name);
  }
</script>

<form on:submit|preventDefault={handleSubmit}>
  <input type="text" bind:value={name}>
  <button type="submit">Submit</button>
</form>

Enter fullscreen mode Exit fullscreen mode

In this example, we are using the bind:value directive to bind the value of the text input to a variable called name. The on:submit|preventDefault directive is used to attach a submit event to the form, which calls the handleSubmit function when the button is clicked. The preventDefault modifier is used to prevent the default behavior of the form, which is to refresh the page.

Working with Stores

Svelte also allows you to create global stores, which can be used to share states across multiple components. In the following example, we'll create a store for a user's name and age and use it in multiple components.

Create a folder inside src called stores, and inside that folder create a main.js, this will be our main store for this application, you can have multiple stores that can do multiple things, but for the sake of simplicity, we will keep this short.


// stores/main.js
import { writable } from "svelte/store";

export const name = writable("");
export const age = writable(0);

Enter fullscreen mode Exit fullscreen mode

After that create another folder called components, we will create two Svelte files, one called ComponentA.svelte and the other will be called ComponentB.svelte, you can call the components whatever you like.

In the first component, we are going to get the name from the store and updated it to something else on that component.

To subscribe to a store value, you just need to prepend $ to each variable.


<!-- Component A -->
<script>
    import { name } from '../stores/main.js';
</script>

<form>
    <label for="name">Name: </label>
    <input id="name" type="text" bind:value={$name}>
</form>

Enter fullscreen mode Exit fullscreen mode

Now in the second component, we are going to get the age from the store and updated it to something else on that component.


<!-- Component B -->
<script>
    import { age } from '../stores/main.js';
</script>

<form>
    <label for="age">Age: </label>
    <input id="age" type="number" bind:value={$age}>
</form>

Enter fullscreen mode Exit fullscreen mode

After that, we can go back to our App.svelte file, remove all of its contents and import the two components:


<script>
  import ComponentA from "./components/ComponentA.svelte";
  import ComponentB from "./components/ComponentB.svelte";
  import { name, age } from "./stores/main.js"
</script>

<ComponentA />
<ComponentB />

<h1>Hello I'm {$name}, and I'm {$age} years old</h1>

Enter fullscreen mode Exit fullscreen mode

In this example, we have created two stores for a user's name and age in the stores/main.js file. We then import and use these stores in two different components. We use the bind:value directive to bind the input value to the store. As you can see, the value of the store is reactive and will change if the input is changed.

In summary, Svelte is a powerful and easy-to-use JavaScript framework for building web applications. It allows you to work with forms, reactive states, and stores in a simple and intuitive way. This guide should give you a good starting point for building your own Svelte applications.

Top comments (0)