Welcome to the third lesson of our "Building A Kanban Board" course! In our previous lessons, we set up our task store using Svelte's Runes API and created the visual components to display our tasks in a Kanban board layout. Now it's time to make our application interactive by allowing users to add new tasks.
A key feature of any task management application is the ability for users to create new tasks. Without this functionality, our Kanban board would be static and not very useful in real-world scenarios. By adding a form component, we'll transform our application from a simple display of tasks to an interactive tool that users can use to manage their work.
Lesson Objectives
By the end of this lesson, you'll understand how to:
Enhance our task store with functionality to add new tasks
Create a form component with proper validation
Manage form state using Svelte's Runes
Connect user input to our application state
Let's get started by adding the necessary functionality to our task store!
Enhancing the Task Store with Add Functionality
In our first lesson, we created a task store that manages our application's state. Now, we need to enhance this store with the ability to add new tasks. Let's update our taskStore.svelte.js file to include this functionality:
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Understanding the addTask Function
The key addition here is the addTask function, which takes a title and an optional description as parameters. Let's break down what this function does:
It creates a new task object with a unique ID (using Date.now() to generate a timestamp), the provided title and description, and a default status of "todo."
It adds this new task to our tasks array using the push method.
It returns the newly created task, which can be useful if we need to reference it later.
Notice that we're using Date.now() to generate a unique ID for each task. This is a simple approach that works well for our purposes, but in a production application, you might want to use a more robust ID generation method, such as a UUID library.
We're setting the default status to "todo" because new tasks typically start in the "To Do" column of a Kanban board. This makes sense from a user experience perspective, as tasks usually begin in the planning stage before moving to "In Progress" and eventually "Done."
Because our tasks array is reactive (created with $state), any changes to it will automatically trigger updates to our derived values (todoTasks, inProgressTasks, and doneTasks). This means that when we add a new task, it will automatically appear in the appropriate column of our Kanban board without any additional code.
Now that we have the functionality to add new tasks, let's create a form component that users can interact with.
Building the TaskForm Component Structure
Let's create a new file called TaskForm.svelte in the src/components directory. This component will contain a form with inputs for the task title and description:
In the script section, we're importing the addTask function from our task store. We're also creating two reactive variables using $state: title and description, which will hold the values of our form inputs. Additionally, we're creating a derived value characterCount that tracks the length of the description, which we'll use to display a character counter.
Form Submission Handler
We've defined a handleSubmit function that will be called when the form is submitted. This function:
Prevents the default form submission behavior
Checks if the title is not empty (after trimming whitespace)
If valid, calls the addTask function with the title and description values
After adding the task, resets the form inputs to empty strings
Form Structure
In the markup section, we're creating a form with the onsubmit attribute set to our handleSubmit function. Inside the form, we have two form groups:
Title Input Group: Contains a label and an input field for the task title. We're using the bind:value directive to create a two-way binding between the input value and our title variable. We've also added the required attribute to ensure the user provides a title.
Description Input Group: Contains a label and a textarea for the task description. Again, we're using bind:value to create a two-way binding with our description variable. We've also added attributes to limit the textarea to 3 rows and a maximum of 200 characters.
The label for the description includes a span that displays the current character count and the maximum allowed characters. This provides immediate feedback to the user about how much text they can still enter.
Finally, we have a submit button that triggers the form submission when clicked.
Form Design Best Practices
This structure follows best practices for form design:
Each input has an associated label with a matching for attribute, which improves accessibility
We're using semantic HTML elements (form, label, input, textarea, button), which helps with accessibility and SEO
We're providing placeholder text to guide the user on what to enter
We're validating input (requiring a title) to ensure data quality
We're providing feedback (character count) to help the user understand constraints
Now that we have the basic structure of our form, let's look at how we're managing its state.
Managing Form State with Runes
Reactive State and Two-Way Binding
In our form markup, we're using the bind:value directive to create a two-way binding between our form inputs and these state variables:
This means that when the user types in these inputs, our state variables will automatically update. And if we programmatically change these variables (as we do after submitting the form), the input values will update to reflect the new state.
We're also using our derived characterCount value in the UI to display a character counter:
This provides immediate feedback to the user about how many characters they've entered and how many they can still enter. Because characterCount is derived from description, it will automatically update as the user types, without any additional code.
This is a great example of how Svelte's reactivity system makes it easy to create dynamic, responsive UIs with minimal code. By declaring our dependencies and letting Svelte handle the updates, we can focus on the logic of our application rather than the mechanics of updating the UI.
Handling Form Submission
Now let's look at how we handle form submission in our TaskForm component:
function handleSubmit(e) { e.preventDefault(); if (title.trim()) { addTask(title, description); title = ''; description = ''; }}
This function is called when the form is submitted by clicking the submit button or pressing Enter in the title input field. (Note: pressing Enter in the description textarea won't submit the form since it's used for adding new lines.) Let's break down what this function does:
e.preventDefault(): This prevents the default form submission behavior, which would cause the page to reload. Instead, we want to handle the submission in JavaScript.
if (title.trim()): We check if the title is not empty after trimming any whitespace. This is a simple validation to ensure we don't add tasks with empty titles.
addTask(title, description): If the title is valid, we call the addTask function from our task store, passing the title and description values.
title = ''; description = '';: After adding the task, we reset the form inputs to empty strings. This provides a clear visual indication to the user that their task has been added and prepares the form for the next entry.
In our form markup, we connect this function to the form's submit event:
<form onsubmit={handleSubmit} class="task-form"> <!-- form content --></form>
Form Submission and Validation
By using the onsubmit attribute, we ensure that our function is called whenever the form is submitted, regardless of how the submission is triggered (button click or Enter key).
This pattern of form handling is common in modern web applications:
Prevent the default form submission
Validate the input
Process the data (in this case, add a new task)
Reset the form
By following this pattern, we create a smooth, intuitive user experience that doesn't require page reloads and provides immediate feedback.
It's worth noting that we're doing minimal validation here (just checking if the title is not empty). In a production application, you might want to add more robust validation, such as checking for duplicate task titles or validating the format of certain fields. However, for our purposes, this simple validation is sufficient.
Styling the Form Component
Now let's add some CSS to make our form look nice and be consistent with the rest of our application:
These styles create a visually appealing and user-friendly form:
Form Container:
Light background, rounded corners, and a subtle shadow to make it stand out
Centered on the page with a limited width of 500 pixels for optimal readability
Flexbox arrangement for vertical element layout with consistent spacing
Input Fields:
Labels styled to be smaller and lighter to create visual hierarchy
Character count styled even lighter and smaller for subtle feedback
Consistent padding, border-radius, and font size across inputs
Focus states that change border color and add a subtle glow for clear interaction feedback
Submit Button:
Blue background with white text that stands out as a call to action
Hover effect that darkens the blue slightly to indicate interactivity
Styling that matches the overall form design while remaining prominent
These styles create a clean, modern look that's consistent with the rest of our application. The form is easy to read and use, with clear visual feedback for interactions like focusing on an input or hovering over the button.
Integrating the Form into our Application
To use our TaskForm component, we need to import it in our main page component and add it to the markup. Here's how we would update our +page.svelte file:
By placing the TaskForm component above the Board component, we create a natural flow where users first see the form to add new tasks and then see the board with all tasks. This is a common pattern in user interface design that follows the natural workflow of first creating items and then viewing them.
Page Structure
The page layout is simple and focused:
A container with a maximum width and centered on the page
A title that clearly identifies the application
The TaskForm component for adding new tasks
The Board component for displaying tasks in columns
This structure creates a clean, focused user interface that guides the user through the process of managing their tasks.
In our TaskForm component, we're using Svelte's Runes API to manage the state of our form inputs. Let's take a closer look at how this works:
JavaScript
let title = $state('');let description = $state('');const characterCount = $derived(description.length);
Here, we're creating two reactive variables using the $state rune:
title: Initialized as an empty string, this will hold the value of the title input.
description: Also initialized as an empty string, this will hold the value of the description textarea.
We're also creating a derived value using the $derived rune:
characterCount: This is calculated based on the length of the description. Whenever the description changes, this value will automatically update.
This is a simple but powerful pattern for managing form state in Svelte. By using $state, we ensure that changes to these variables will trigger updates to any part of the UI that depends on them. And by using $derived, we can create computed values that automatically update when their dependencies change.
In this lesson, we've transformed our static Kanban board into an interactive application by adding the ability for users to create new tasks. Here's what we've accomplished:
Enhanced our task store with the addTask() function that creates new tasks with unique IDs and adds them to our reactive state
Built a TaskForm component that collects user input for task titles and descriptions
Leveraged Svelte's Runes API to manage form state with $state variables and computed values with $derived
Implemented form validation to ensure users provide essential information
Added visual feedback through styling and a character counter for the description field
Connected the form to our application state so that new tasks automatically appear on the board
This implementation demonstrates the power of Svelte's reactive programming model. By declaring our dependencies using Runes, we've created a system where changes to one part of our application (the form) automatically update another part (the board) without any additional code.
In the next lesson, we'll continue enhancing our Kanban board by allowing users to move tasks between columns to reflect their changing status.