How to Create Components in Svelte

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 n…


This content originally appeared on DEV Community and was authored by Johnny Simpson

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.

An example of how components work in Svelte

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. 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 />

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:

<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.


This content originally appeared on DEV Community and was authored by Johnny Simpson


Print Share Comment Cite Upload Translate Updates
APA

Johnny Simpson | Sciencx (2022-03-29T11:07:59+00:00) How to Create Components in Svelte. Retrieved from https://www.scien.cx/2022/03/29/how-to-create-components-in-svelte/

MLA
" » How to Create Components in Svelte." Johnny Simpson | Sciencx - Tuesday March 29, 2022, https://www.scien.cx/2022/03/29/how-to-create-components-in-svelte/
HARVARD
Johnny Simpson | Sciencx Tuesday March 29, 2022 » How to Create Components in Svelte., viewed ,<https://www.scien.cx/2022/03/29/how-to-create-components-in-svelte/>
VANCOUVER
Johnny Simpson | Sciencx - » How to Create Components in Svelte. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/03/29/how-to-create-components-in-svelte/
CHICAGO
" » How to Create Components in Svelte." Johnny Simpson | Sciencx - Accessed . https://www.scien.cx/2022/03/29/how-to-create-components-in-svelte/
IEEE
" » How to Create Components in Svelte." Johnny Simpson | Sciencx [Online]. Available: https://www.scien.cx/2022/03/29/how-to-create-components-in-svelte/. [Accessed: ]
rf:citation
» How to Create Components in Svelte | Johnny Simpson | Sciencx | https://www.scien.cx/2022/03/29/how-to-create-components-in-svelte/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.