Introduction to SvelteJS

Lee McGowan
Feb 4 · 8 min read

There’s a lot to be said for going back to basics. Over the years, web development has evolved from simple HTML to HTML and javascript, to jQuery, and then to frameworks like Angular and React. Many of these developments have been innovative and some great ideas have come out of them, like the web-component model. But it’s fair to say things have gotten a lot more complicated too.

SvelteJS takes you right back to the beginning. It’s a framework but not in the usual sense. It doesn’t add lots of new stuff and there’s very little to learn. All it does is build your code into a series of optimized javascript instructions. Most of the work is done during compilation so that there’s very little happening in the browser at runtime. This makes for a lightning-fast application with a small footprint.

This article will focus on introducing Sveltejs through a quiz app. It will show you a picture of an animal or Boris Johnson — you’ve got to guess which is which. If you answer correctly, you get to keep the animal, and it gets added to a list at the bottom of the page. What is the point of this nonsense, I hear you ask? Well, there is none. Just like there’s no point to my depressing existence.

Creating Your Project

Make sure you have node and npm, then run:

npm i npx

NPX is a tool that lets you directly execute npm package binaries without downloading them. Once that’s complete, run:

npx degit sveltejs/template test-project

This will create a svelte project called test-project. If you want to install into your current folder then you can replace the name with .:

npx degit sveltejs/template .

Once that’s done, run:

npm install && npm run dev

Now, go to localhost:5000. You should see something like this:

If you do, everything is working. If you don’t, start panicking and call the cops.

What the Generator Created

Svelte is lightweight, and so is the generated project. All you get is a src folder where your code will live. There’s also a rollup.config.js which performs a similar function to a webpack config. Lastly is the public folder, which holds all your static files like the HTML, CSS and built javascript.

If you look in your node_modules folder, you’ll notice it’s relatively small. This might be a breath of fresh air for some people (cough, create-react-app, cough).

Svelte Entry Point

The entry point to your application is in src/main.js.

Here we’re creating a Svelte application and saying that we want the App component to be rendered within the <body /> tags of the main HTML document.

The props object defines the data we want to pass to the component.

Our First Component

Svelte follows the web-component paradigm, just like React. Take a look at src/App.svelte.

This is all a Svelte component is. A script tag with your javascript, a style tag with your CSS – scoped to only that component – and your HTML. But the initial one we’re given is a little busy, so let’s delete everything till you’re left with a blank page. Now, enter the following:

<h1>Old MacDonald's Playground</h1>

Yes. Just that. Only that. That alone is a component. No fluff. No excess. Let’s move on.

The RandomImage Component

The RandomImage component will display a picture and ask you to say whether it’s an animal or not. My non-animal pictures will be of Boris Johnson. You don’t have to do this, but I want my quiz to be really difficult.

I’m going to create a file to store all of my images. I’ll put this in src/images.js. If you can’t be bothered finding your own, then you can copy mine from below (but really? lazy.):

Displaying the Random Image

Create a new component, RandomImage.svelte in the src folder. Add the following code:

We put our javascript within the script tags. All we’re doing is importing images and then choosing a random one. We’ve wrapped the code in a function so we can call it again when we need to update the image.

We also have style tags, where we’re constraining the image size.

Lastly, we’re rendering an h2 and the image. Easy, right?

Adding the Click Handlers

We need two buttons, so our players can choose what they think the image shows. Each will have a handler function attached to its click event. The code for that is below. This goes between the script tags too.

This is just regular javascript. In the end, we call getRandomImage so we can update when the user gives an answer. We will use notification to display a message later.

Adding the Buttons

Beneath the img tag, add:

<button on:click={() => choose('animal')}>EE-I-EE-I-OH</button><button on:click={() => choose('boris')}>Brexit Means Brexit</button>

By including the curly brackets, Svelte understands that we’re referencing something defined within the script tags. In this case, our choose function. So all we’re doing here is creating buttons and attaching handlers. Who said this programming stuff was supposed to be hard?

Adding the Notification

The notification will let the user know whether they got the last question right. Adding it will introduce a new concept: conditionals. Svelte’s way of handling conditionals is slightly different to some other popular frameworks and takes a little getting used to, but once you’ve spent some time doing it I think you’ll see just how intuitive it is.

We only want to show our notification if it isn’t empty. In the HTML, just above the h2, add the following:

{#if notification.length > 0}
<div class="notification">{notification}</div>
{/if}

Svelte will render the stuff between #if and /if when the provided condition is true. So in this case we’re rendering a notification if the notification string isn’t empty. We don’t need to use an else block here, but just so you know what it looks like, I’ve done it below.

{#if notification.length > 0}
<div class="notification">{notification}</div>
{:else}
<div>This is an else!</div>
{/if}

Your component will work now, but it won’t do anything useful. I said above that we want to render a list of the animals the player has won at the bottom of the page. But we don’t want to do that in this component, which means we need a way of telling the parent component if we won an animal. We do that by dispatching events.

Within <RandomImage />'s script tags, add the following:

import { createEventDispatcher } from 'svelte';

This is a helper function that lets us dispatch events to the parent component. We create a dispatch method by calling createEventDispatcher, and then we can emit events by calling dispatch. Any emitted event will then be accessible in the parent component, alongside any data passed with it. That looks like this.

const dispatch = createEventDispatcher();dispatch('event-name', eventBody);

Our user can only win animals (who wants a pet Boris?), so we dispatch the event whenever a user gets an animal question right. In the choose function, underneath this line:

notification = “YES! Correct. That is definitely an animal.”;

add the following:

dispatch('addAnimal', image.url);

We dispatch the image URL with the event so that we can render the animal’s picture in the list, as we haven’t recorded any of their names. Why? Because I’m stupid, that’s why.

Anyway, with that done, we can move back to the App component, and start add our list.

The App Component

In App.svelte, add some <script> tags and then import your RandomImage component:

import RandomImage from './RandomImage.svelte’;

Once that’s done, adding it to the page is as easy as sticking <RandomImage /> in your HTML.

Now, if you open your browser and navigate to the page, you should see something like this:

🤩

Intercepting the addAnimal Event

Back in our App component, we can intercept the addAnimal event by adding it to our RandomImage tag like this:

<RandomImage on:addAnimal={addAnimal} />

Animals List and addAnimal Function

Now that we can access the event, we need to create the actual animals list & the handler function we want to call when a user gets a question right. Add this in between <App />’s <script> tags.

let animals = [];const addAnimal = event => {
const animalImgUrl = event.detail;
animals = [...animals, animalImgUrl];
};

Here we retrieve the detail object from event. This holds the data that we passed when calling dispatch. We then add that to the animal's array using array spread syntax. We need to do this. Pushing to the array won’t trigger an update, so you won’t see the changes, therefore we have to completely overwrite it. This is always the case with Svelte, and not really a bad thing as it means we’re not mutating data.

The Animals Component

Create a new component in the src/ folder called Animals.svelte, and add the following code:

<script>
export let animals;
</script>

This is how we tell Svelte which props a component expects. We can now pass an animals prop to the component and it will pick it up. But first, we want to loop through the list and render the animal pictures.

At this point, we need to introduce another new bit of Svelte syntax. Again, it can be quite weird at first, but hopefully you will come to see how nice it is.

In the HTML of <Animals/>, add the following:

I’ve added an if statement here so we don’t try to render the list when the animals array is empty, but the important part is this:

{#each animals as animal}
<img src={animal} alt="An animal" />
{/each}

This is how you render a list in Svelte. The statement will loop over each element in the animals array and then assign it to a temporary animal variable (which you can call anything). Then for each of those, it will return the stuff within the block. It’s basically the same as array.map(item => <div>{item}</div>); in jsx, but I prefer it this way.

Rendering the Animals Component

All we have to do now is render the <Animals /> component. In <App />, import the new component:

import Animals from ./Animals.svelte

and then render it beneath <RandomImage /> like so:

<Animals animals={animals} />

And that’s it. You should now see your animals rendered. If you can get the answers right, of course.


This was a very brief introduction to Svelte, but you’ve actually learned almost everything you need to build powerful apps. Let’s review. We went over:

  • How to write a component
  • How to render a component within another
  • How to define expected props
  • How to pass props to components
  • How to do conditionals
  • How to do loops
  • How to fire events
  • How to intercept events
  • How to attach handlers to events

I mean, that’s a lot of stuff. There is more but these tools are the really important ones, and with them, you can create some really cool stuff. Svelte’s beauty is in its simplicity, and I hope you can see that after reading this article. React is great and it’s gonna dominate for a long time, but there is a place for technologies like this, and sometimes real innovation happens when you go back to basics.

Thanks for reading.

If you want to see the finished source code for this article, you can find it here.

The Startup

Medium's largest active publication, followed by +586K people. Follow to join our community.

Lee McGowan

Written by

I write about programming, and I write about writing. I also might write about philosophy, if I ever get ‘round to engaging my tiny brain.

The Startup

Medium's largest active publication, followed by +586K people. Follow to join our community.

More From Medium

More from The Startup

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade