Svelte

How to Create Components in Svelte

📣 Sponsor

In my last article, we looked at how to make your first Svelte application using SvelteKit. Today we'll look at the next step - how to make components, so you can start to build real Svelte applications.

What are components, and why do we need them?

Components are a common theme in all modern frontend frameworks. Essentially, as we started to build more and more complicated applications, we found that we were reusing the same types of things all the time. For example, a registration form may appear in multiple different places, and use exactly the same code.

Components ultimately try to deal with that problem. We create these reusable pieces of code, and put them where ever we want them to appear. That way, we only write the code once, and can put it anywhere we like. Components act like a custom HTML tag in Svelte, which can be added anywhere we want it to appear.

How components work in Svelte

How to make components in Svelte

Before you start, make sure you've set up a new Svelte project using SvelteKit. Within SvelteKit, we already have a folder called routes, which contains all of our Svelte application pages. To kick things off, make a new folder in src called components. We'll store all of our components here.

Make a new file, and call it MyFirstComponent.svelte - this will act as our first Svelte component. If you followed my last tutorial, our folder structure will now look like this:

static                   <-- where we store all of our public assets like favicons, images, and fonts
|- favicon.png           <-- our favicon
tests                    <-- a folder to store our tests
|- test.js               <-- an example test using @playwright
src                      <-- our main Svelte app files
|- routes                <-- a folder to store all of our routes in
|- components            <-- a folder for all of our components
|-- MyFirstComponent.vue <-- our first component
|-- index.svelte         <-- our index route file. This will be the file displayed at the route of the site
|- app.d.ts              <-- our core Svelte app file
|- app.html              <-- our main index file where the app will appear
.gitignore               <-- files we wish to ignore for git
.npmrc                   <-- config file for npm
.prettierrc              <-- config file for prettier
.eslintrc.cjs            <-- config file for eslint
package.json             <-- our NPM installed packages
playwright.config.js     <-- config file for playwright
svelte.config.js         <-- config file for svelte itself
tsconfig.json            <-- config file for typescript

Great, now we have a file, let's start working on making our first component.

Creating our Svelte Component

For this guide, I'm going to be making a simple counter component which can have a preset default value. The nice thing about Svelte is that the files look and feel exactly like regular CSS, HTML, and Javascript code.

As such, to create a simple counter, we start with just that:

<script> // we write export let to say that this is a property // that means we can change it later! export let x = 0; const addToCounter = function() { ++x; } </script> <button id="counter" on:click="{addToCounter}">{x}</button> <style> button { background: #ffb334; border-radius: 8px; border: none; font-weight: bold; cursor: pointer; padding: 0.5rem 2rem; color: white; font-size: 1.5rem; } </style>

Svelte works a lot like other frameworks, except the code for components is massively simplified in my opinion.

Click Event

Above we simply have added one event, click, and we can add events to any DOM element by using the on:event={functionName} syntax. Above, we've added on:click={addToCounter} to signify that we will run addToCounter() anytime someone clicks the button.

Properties

In move HTML we have properties or props. For example, we can set the href property of an <a> tag to set it's link. If we want to create custom props in Svelte, we add it to our component's Javascript using the export keyword:

export let x = 0;

That means we can use it as a prop when we use it - speaking of which, let's look at how we would implement this in our Svelte project.

Using Components in Svelte

Now that we've created a basic component, we can add it anywhere we like. Let's try adding it to routes/index.svelte. You can import and use your new component like so:

<script> import MyFirstComponent from "../components/MyFirstComponent.svelte"; </script> <MyFirstComponent /> </code></pre> <p>Now we have a simple counter we can add anywhere to our application. Even better, we can change the default value, since we defined the <code>addToCounter</code> number as a <strong>prop</strong> in our component:</p> <pre><code class="javascript"> &lt;MyFirstComponent x={5} /> </code></pre> <p><strong>Now the component will show 5 as its first value</strong>, rather than 0!</p> <h3>Testing it out</h3> <p>If you've <a href="https://fjolt.com/article/svelte-creating-your-first-app" target="_blank">created your Svelte application based on our original tutorial</a>, you can now test your components by running the following command in terminal:</p> <pre><code class="shell"> npm run dev </code></pre> <p>You'll now have a dev instance of your code available at <strong>http://localhost:3000</strong>.</p> <h2>Conclusion</h2> <p>Creating Svelte applications and new components is easy, and Svelte is such a lightweight language that you might not even realise you're not just using HTML, CSS and Javascript. I hope you've enjoyed this quick introduction into Svelte components. Stay tuned for more <a href="https://fjolt.com/category/svelte" target="_blank">Svelte content</a>.</p></body></html>
Last Updated 1648551375314

More Tips and Tricks for Svelte

Subscribe for Weekly Dev Tips

Subscribe to our weekly newsletter, to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email