Read To the end there are Rewards
Introduction
SvelteKit is the best framework to build a fast lightweight web apps, this is why I am going to publish a series of posts about svelte and how to build apps with it.
What we going to build:
Today we are building a to-do app using SvelteKit, and we will implement the CURD operation ( Create, Update, Read, Delete).
it will be simple and fast.
Tools
- Vite.
- SvelteKit
- NPM package manager
Setup
GitHub Repo If you want to follow along.
create-svelte
Everything you need to build a Svelte project, powered by create-svelte
.
Creating a project
If you're seeing this, you've probably already done this step. Congrats!
# create a new project in the current directory
npx create-vite@latest
Developing
Once you've created a project and installed dependencies with npm install
(or pnpm install
or yarn
), start a development server:
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
Building
To create a production version of your app:
npm run build
You can preview the production build with npm run preview
.
first, we will use vite to create a new svelte app if you don't have it installed yet, please click here.
$ npx create-vite@latest
First, you will write the name of the app, for it will be “to-do”, Second, you have to choose the framework, and we will choose Svelte, After that, we will Choose our variant, which is SvelteKit, It should look like this.
The Variant.
After that, you will be asked how you want your app set up make sure the answer is exactly the same as pointed out in the screenshot down.
Now your app is ready for development.
Fire Up the server
now you need to start the server so follow the given commands bellow
1. $ cd To-do #Your project folder
2. $ npm install # I use 'npm i' only because I am lazy :)
3. $ npm run dev
Your Terminal should be like this.
Now open your favorite editor, mine is Neovim.
First component: Todo-form
open the src
Directory and add a new folder call it components
, inside that folder, add a new file call it Todo-form.svelte
, open it, copy the code down below and I will explain every line.
<!-- TodoForm.svelte -->
<script>
export let addTodo;
let todoText = '';
function handleSubmit(event) {
event.preventDefault();
addTodo(todoText);
todoText = '';
}
</script>
<form class="bg" on:submit|preventDefault={handleSubmit}>
<input type="text" bind:value={todoText} placeholder="Add a todo..." />
<button type="submit">Add</button>
</form>
The export let addTodo;
export a property named addTodo
from the component. This allows the parent component to bind a function to the addTodo
property, which will be called when the form is submitted.
The let todoText = '';
declares a local variable named todoText
and sets its initial value to an empty string. This variable is used to store the value of the input field.
The handleSubmit(event)
function is called when the form is submitted. It is passed an event object representing the form's submission event. Inside the function, the following things happen:
-
event.preventDefault()
is used to prevent the browser's default behaviour when a form is submitted, which would be to refresh the page. -
addTodo(todoText)
is called with the current value oftodoText
as an argument. This function is passed into the component via theaddTodo
property and is expected to handle adding the new todo. -
todoText = '';
clears thetodoText
variable, so the input field is ready for the next todo item.
In the <form>
tag, the class="bg"
sets the form's background colour to be the background colour. The on:submit|preventDefault={handleSubmit}
uses Svelte's event handling system to attach the handleSubmit
function as an event handler for the form's submit
event, and also prevent the default submission behaviour of the form.
The <input>
element has bind:value={todoText}
which binds the value
property of the input element to the todoText
variable so that any changes made to the input field will be reflected in the variable, and vice versa. The placeholder
attribute sets a placeholder text for the input field.
The <button type="submit">
has Add
as the label for the button which on clicking it triggers the submit event and calls the handleSubmit function.
Second Component: Todo-list:
Now add another file call it Todo-list.svelte
, Then copy and paste this code:
<!-- TodoList.svelte -->
<script>
export let todos = [];
export let deleteTodo;
</script>
{#each todos as todo}
<div class="todo">
<div class="todo-text">{todo.text}</div>
<button class="todo-delete" on:click={() => deleteTodo(todo.id)}> Delete </button>
</div>
{/each}
This code is a Svelte component that defines a template for rendering a list of todo items, as well as an accompanying script. The component accepts two props, todos
and deleteTodo
.
In the script, the todos
and deleteTodo
props are declared using the export
keyword, indicating that they are expected to be passed down from a parent component.
The template part of the component uses the Svelte's {#each}
directive to render a div
element for each item in the todos
array. Inside the {#each}
block, there is another div
element with a class of "todo" that contains two children elements.
The first one is a div
element with a class of "todo-text" that displays the "text" property of the todo item, And the second one is a button
element with a class of "todo-delete" that has an on:click
event listener that is triggered when the button is clicked, when it happens, it will call the function passed down in the deleteTodo
prop, passing the "id" property of the current todo item as an argument.
This way, when the button is clicked, it will call the deleteTodo
function and pass the id of the todo item, This makes it easy to delete the specific todo item from the list.
Add components to the main Page
Now we need to add the components to the page we want in order to be rendered to the browser, You will find a folder called routes
inside the src
folder, open the file inside of it called +page.svelte
, I want you to copy this:
<!-- App.svelte -->
<script>
import TodoList from '../components/Todo-list.svelte';
import TodoForm from '../components/Todo-form.svelte';
let todos = [
{ id: 1, text: 'Wellcome' },
{ id: 2, text: 'To' },
{ id: 3, text: 'my Todo' },
{ id: 4, text: 'app' }
];
let text;
function addTodo(text) {
todos = [...todos, { id: Date.now(), text }];
}
function deleteTodo(id) {
todos = todos.filter((todo) => todo.id !== id);
}
</script>
<div class="todo-container">
<TodoForm {addTodo} />
<div class="todo-list">
<TodoList {todos} {deleteTodo} />
</div>
</div>
<style>
.todo-list {
margin-top: 5rem;
}
.todo-container {
max-width: 100vw;
display: grid;
place-items: center;
}
</style>
Explanation
At the top of the script, the code imports two Svelte components: TodoList and TodoForm. These components are likely defined in other files in the same directory.
Then there is a variable called todos
which is an array of todo objects with properties id
and text
and another variable called text
which is empty.
The code also defines two functions:
-
addTodo
function that takes in a parameter calledtext
, create a new todo object with a unique id and the text, and add it to the array of todos. -
deleteTodo
function that takes an id and filter out the object from the array of todos which have that id.
Then there is a div with the class "todo-container" that contains two elements. One is the TodoForm component, passed the addTodo
function as a prop. The other element is a div with the class "todo-list" that contains the TodoList component.
This component passed two props: {todos} and {deleteTodo} which allows the component to use the array of todos and deleteTodo function.
The Final step:
open the browser and type in the search bar https://localhost:5173
, you should see the result for all the copy and paste up there.
Free
Thank you for reading this post. I hope it helps you and becomes a fan of this framework (SvelteKit). Here are your rewards. A little book about clean code and how to implement it. It's free.
Top comments (0)