OneCompiler

Building a todo list in Svelte

224


In this post, let's see how to build a todo list using Svelte.

Setup the project

Run the below commands to start a empty svelte project.

npx degit sveltejs/template svelte-todolist && cd svelte-todolist

Now install the required dependencies

yarn install

Creating the components

Create a folder components where all our svelte components reside.

Building the header

Paste the below code into the header.svelte file

<div class="header">
    <h3>Svelte Todo list</h3>
</div>

<style>

    .header {
        background-color: orange;
        padding: 1px;
        margin: 0px;
        color: black;
        text-align: center;
        font-size: 15px;
    }

</style>

Building the todo component

Create a file called todo.svelte and paste the below code

<script>
    let title = ''
    let todos = []

    const addTodo = () => {
        todos = [...todos, {
            "name": title,
            "id": Math.random()
        }]
    }
</script>

<div class="container">
    <div class="box">
        <input bind:value={title} type="text" placeholder="Enter todo" />
        <button on:click={addTodo}>Add</button>
    </div>
    <h2 style="text-align:center">Todos</h2>
    <hr />
   <div class="todos">
    {#each todos as todo}
            <p class="todo-item">{todo.name}</p>
        {:else}
            <p>No Todos</p>
        {/each}
   </div>
</div>

<style>
    .container {
        width: 80%;
        margin: 0 auto;
    }
    .box {
        padding: 10px;
        display: flex;
        justify-content: space-around;
        margin: 10px auto;
    }

    input {
        padding: 10px;
        width: 60%;
        font-family: 'Segoe UI';
        font-weight: bold;
    }

    button {
        padding: 3px 20px;
        border: none;
        background-color: tomato;
        font-family: 'Segoe UI';
        font-weight: bold;
        color: white;
        box-shadow: 2px 2px 5px #ccc;
        border-radius: 4px;
    }

    .todo-item {
        background-color: blue;
        padding: 10px;
        border-radius: 4px;
        box-shadow: 2px 2px 5px #ccc;
        margin: 10px;
        color: white;
        text-align: center;
        width: 50%;
        margin: 20px auto;
    }

    .todos {
        margin: 20px;
    }
</style>

Now open the App.js file and import the components.

<script>
	import Header from './components/Header.svelte'
	import Todo from './components/Todo.svelte';
</script>

<main class="con">
	<Header />
	<Todo />
</main>

<style>
	
</style>

Run the app with below command.

npm run dev