Obinna Ekwuno Writer of all things technical and inspirational. Developer and Community Advocate. In a love-love relationship with JavaScript🔥

How to build a simple Svelte app

7 min read 2107

Build Simple Svelte App

Editor’s note: This article was last updated on 28 June 2022 to reflect updated information about SvelteKit and Svelte Native.

In the world of JavaScript, a new framework is released almost every day. Generally, the ideas behind them are similar, offering few significant improvements. Modern UI component-based frameworks and libraries include React, Vue, and Angular to name a few.

In this article, we’ll explore Svelte, which takes a different approach to constructing user interfaces. As an example, we’ll build a bookstore app that keeps track of available book titles. We’ll also explore what sets Svelte apart from other frameworks.

To follow along with this article, you’ll need the following:

  • Node.js ≥v6.x installed on your machine
  • npm installed on your machine
  • Familiarity with HTML, CSS, and JavaScript

You can also access the full source code. Let’s get started!

What is Svelte?

Svelte is a frontend web development framework that was released in 2016 by Rich Harris. Svelte is a radical new approach to building user interfaces that can be used to develop either small pieces of an interface or whole applications. We can either begin building our application with Svelte or incrementally integrate it into an existing application.

Building a bookstore app with Svelte

Getting started

There are several ways to get Svelte up and running for a project. In this tutorial, we’ll use degit, a software scaffolding tool. To get started, run the following commands:

npx degit sveltejs/template {project name }

In this case, we name our project svelte-bookstore:

npx degit sveltejs/template svelte-bookstore

Navigate into the project directory:

cd svelte-bookstore

Install the required dependencies:

npm install

Finally, start the application:

npm run dev

Start Svelte Application Degit

The code above creates a boilerplate “Hello, World!” application. The main.js file is the entry point of the app. It initializes the App component and passes it a prop called name:

import App from './App.svelte';
const app = new App({
    target: document.body,
    props: {
        name: 'world'
    }
});
export default app;

The App component is written in App.svelte. Keep in mind that components in Svelte are saved with a .svelte extension. The prop name is declared in the script section as a regular variable, but it is prepended with an export statement that marks it as a prop. It is used inside the HTML by surrounding it with curly braces:

<script>
    export let name;
&lt;/script>
<style>
    h1 {
        color: purple;
    }
</style>
<h1>Hello {name}!</h1>

Creating a dynamic Book component in Svelte

When creating components, there are a few things that are noteworthy about Svelte. For one, styles are scoped within components, so a div styled in one component will not affect another div in a different component. Additionally, we can define functions that are connected dynamically.

In this section, we’ll create a dynamic event with Svelte and link the book.svelte component with app.svelte and passing props. The first step is setting up the Book component and exporting variables, which can be set from the parent tag in app.svelte:

<script>
    export let bookTitle;
    export let bookPrice;
    export let bookDescription;
</script>
<style>
    div{
        margin: 1rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26)
    }
    h1{
        font-size: 1.25rem;
        margin: 0.25rem 0;
    }
    h2{
        font-size: 1rem;
        margin: 0.25rem 0;
        color: aqua;
    }
    p{
        margin: 0.25rem 0;
    }
    button{
        font : larger;
        padding: 0.15rem 0.5rem;
        background-color: #1b1a1a;
        border: 1px solid  aliceblue ;
        cursor: pointer;
        color: white;
    }
&lt;/style>

<div>
    <h2> {bookTitle} </h2>
    <p> {bookPrice}</p>
    <p> {bookDescription}</p>
    <button> Add </button>
</div>

In the code block above, we have variables that are being used in the tags in the div with values coming from app.svelte. Most of the dynamic manipulations happen in this code segment.

In the app.svelte file, we imported the Book component where we’ll do a lot of the dynamic manipulation:

<script>
    import Book from './book.svelte'
    let title = '';
    let price = 0;
    let description = '';
    function setTitle(event){
        title = event.target.value;
    }
</script>
<style>
    h1 {
        color: purple;

    }
    section{
        margin: auto;
        width :30rem;

    }
    label,input,textarea{width: 100%}
</style>
<section>
    <div> 
        <label for="title">Title</label>
        <input type="text" id="title" value={title} on:input={setTitle}/>
    </div>
    <div>
        <label for="price">Price</label>
        <input type="number" id="price" value={price} bind:value={price}/>
    </div>
    <div>
        <label for="description">Description</label>
        <textarea rows="3" id="description" bind:value ={description}/>
    </div>
</section>
<Book bookTitle={title} bookPrice={price} bookDescription={description}/>

From the code block above, we see that inside our script tag, we have also set variables to empty " ". These values are automatically updated. Also notice the setTitle function, which is used to set a title to target the object that calls it within the on:.

We call the function without parentheses because we don’t want it immediately executed. Instead, we are trying to set up a refers so that Svelte can call the function on every keystroke.

We use on: to add event listeners in Svelte. We can use this to listen to the input event, and we use the curly braces to show dynamic input. The function we have uses two-way binding, therefore, we can use it on other tags using the bind operator, which binds the value property to the variable. We also do this for the description.

Finally, we pass the variables to the Book component as props by passing the variables title, price, and description using curly braces {}.

Displaying book information in Svelte

Now that we have a card that updates when we input value, the next step is to make sure that we are able to add books to our bookstore. The first thing we have to do is make our button a stand-alone component in order to be able to use it in the other two components. We do so by creating button.svelte and importing it into the book and app components, respectively:

<style>
  button{
        font : larger;
        padding: 0.15rem 0.5rem;
        background-color: #1b1a1a;
        border: 1px solid  aliceblue ;
        cursor: pointer;
        color: white;
    }

</style>


<button on:click >
    <slot/>
</button>

The on:click attribute in the button tag is used to trigger the forward event to the component that uses the button and will handle the event. Let’s look at an example:

app.svelte
<Button on:click={addBook}>ADD Book</Button>

The command above engages with an addBook function that allows the button to add a new book to the array:

let books =[]

function addBook(){
        const newBook = {
            title : title,
            price : price,
            description: description
        };
        books = books.concat(newBook)
    }

The code above exists inside the script tag. It calls all the book’s properties from the form and concatenates them. We use a concat variable because push does not change the book variable. It only changes the array, but assigning concat to a new value will trigger a change.

We now have an array of books that is displayed conditionally using the special markup that Svelte gives us:

{#if books.length === 0}
    <p>
       No books in stock. 
    </p>
{:else}
    {#each books as book}
        <Book bookTitle={book.title} bookPages={book.price} bookDescription={book.description}/>
    {/each}
{/if}

If the array is empty, it will show No books in stock.

Empty Book Store Notification

Once the user updates, it displays the information on the card:

Add New Book Svelte Array
Add new book

Adding a cart in Svelte

To add a cart to our bookstore app, we will have to make another component called purchase.svelte. In the script tag, we would want to export the books variable so that it can be updated by the book tag by passing the information as props in app.svelte:

Add Cart Bookstore Svelte Example
Adding cart to bookstore

In app.svelte, we add an empty array in the script to hold the purchased books. To add books to these purchases, we will use the buy button in the Book component, add the purchaseBook function to the script, and bind to the button using on:{purchaseBook}.

We then use the create a dispatch function from Svelte’s custom library. Finally, we can link the function to the Book tag by adding the on:buy ={purchaseBook}. This event dispatches from our purchaseBook function.

The differences between Svelte and React

Developers can use both Svelte and React to effectively build web applications. However, while they serve the same overall purpose, there are distinct differences in how they work.

Compiler vs. Virtual DOM

One essential distinction between Svelte and React is that Svelte works more like a compiler, while React operates like a JavaScript library. Svelte does most of its work within the compilation step that takes place during build time. As a result, no overhead framework code is injected into the browser when your program runs in the DOM. Being a compiler, Svelte can offer features that other frameworks can’t, like compile-time accessibility checking.



Syntax

When it comes to its syntax, Svelte sticks close to the familiar conventions of HTML, CSS, and JavaScript, making it simpler to understand and easier to learn than React. Svelte sticks closely to classic web development models and introduces only a few HTML extensions, making it much easier to learn.

To demonstrate, here’s a Counter component written in Svelte:

//language: JavaScript

//Counter.svelte

<script>
  let count = 0;

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

<button on:click={handleClick}>{count}</button>

Unlike Svelte, React has its own syntax called JSX that allows us to write HTML inside the JavaScript code. This pattern betrays conventional practices and can be confusing to learn. Below is the same Counter component in React:

//language: JavaScript

import { useState } from "react";

const Counter = () => {
  const [count, setCount] = useState();

  const handleClick = () => {
    setCount((count) => count + 1);
  };

  return <button onClick={handleClick}>{count}</button>;
};

export default Counter;

Styling

Another great feature about Svelte is that it offers flexible styling by scoping styles to their component. Therefore, we don’t have to bother writing unique classes since Svelte generates them during the compile step. In a scenario where the <p> element appears in multiple components, we don’t need to attach different classes to avoid CSS conflicts.

Learning curve

An advantage of learning Svelte over other frameworks is that Svelte has a shallow learning curve. Web developers with basic HTML, CSS, and JavaScript knowledge should quickly grasp the specifics of Svelte and be able to start building web applications.

Svelte’s growing popularity

Svelte is becoming more popular, and the numbers cannot lie.

In 2021, 68 percent of developers were interested in learning Svelte. With Rich Harris moving to Vercel and Svelte now having the funding and community backing of the Vercel ecosystem, that number is sure to increase. One additional study showed that usage of Svelte has increased from eight percent to 20 percent from 2019 to 2021, a 150 percent growth. Svelte is the first choice for developers in frameworks they would like to learn in the future.

Frameworks in the Svelte ecosystem

SvelteKit

The Svelte ecosystem is developing rapidly, and several other frameworks have been built on top of Svelte. For one, SvelteKit, which was released in March 2021, is a newer framework that replaces Sapper. It is the fastest way to build Svelte apps, and it comes with advanced features like server-side rendering, code splitting, file-based routing, and offline support. SvelteKit is Svelte’s equivalent of Next.js.

Svelte Native

Another example is Svelte Native, which allows Svelte developers to easily build native Android and iOS apps. Svelte Native, which was released in February 2019, combines the best of Native Script and Svelte.

Conclusion

In this article, we learned the basics of Svelte by creating a bookstore app. We reviewed the latest developments in the Svelte ecosystem and saw why companies and development teams are increasingly adopting Svelte into their production workflows.

To get a deeper understanding, be sure to check out Svelte’s interactive documentation. Happy coding!

Get set up with LogRocket's modern React error tracking in minutes:

  1. Visit https://logrocket.com/signup/ to get an app ID.
  2. Install LogRocket via NPM or script tag. LogRocket.init() must be called client-side, not server-side.
  3. $ npm i --save logrocket 

    // Code:

    import LogRocket from 'logrocket';
    LogRocket.init('app/id');
    Add to your HTML:

    <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script>
    <script>window.LogRocket && window.LogRocket.init('app/id');</script>
  4. (Optional) Install plugins for deeper integrations with your stack:
    • Redux middleware
    • ngrx middleware
    • Vuex plugin
Get started now

Get set up with LogRocket's modern error tracking in minutes:

  1. Visit https://logrocket.com/signup/ to get an app ID
  2. Install LogRocket via npm or script tag. LogRocket.init() must be called client-side, not server-side
  3. $ npm i --save logrocket 

    // Code:

    import LogRocket from 'logrocket';
    LogRocket.init('app/id');
    Add to your HTML:

    <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script>
    <script>window.LogRocket && window.LogRocket.init('app/id');</script>
  4. (Optional) Install plugins for deeper integrations with your stack:
    • Redux middleware
    • NgRx middleware
    • Vuex plugin
Get started now
Obinna Ekwuno Writer of all things technical and inspirational. Developer and Community Advocate. In a love-love relationship with JavaScript🔥

Leave a Reply