How to Create Components in Svelte
Tags: javascript, svelte, webdev, tutorial
Published: 2022-03-29 11:07:59

In my last article, we looked at [how to make your first Svelte application using SvelteKit](https://fjolt.com/article/svelte-creating-your-first-app). Today we'll look at the next step - how to make components, so you can start to build real Svelte applications.

![An example of how components work in Svelte](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bj4334usmgfbga7pzvvt.png)
 
## 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 include 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 to make components in Svelte
Before you start, make sure you've [set up a new Svelte project using SvelteKit](https://fjolt.com/article/svelte-creating-your-first-app). 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:

```html
<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:

```javascript
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:

```html
<script>
    import MyFirstComponent from "../components/MyFirstComponent.svelte";
</script>

<MyFirstComponent />
```

Creating a counter component in Svelte with SvelteKit
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 addToCounter number as a prop in our component:

```html
<MyFirstComponent x={5} />
```

Now the component will show 5 as its first value, rather than 0!

### Testing it out
If you've created your Svelte application based on our original tutorial, you can now test your components by running the following command in terminal:

```
npm run dev
```

You'll now have a dev instance of your code available at **http://localhost:3000**.

## Conclusion
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 [Svelte content](https://fjolt.com/category/svelte).