Certainly! Below is a simple Svelte 5 component for a shopping list form. It allows users to add items with quantities, displays the list, and lets users remove items.
<script>
import { reactive } from 'svelte';
// Reactive state for form inputs and shopping list
let item = '';
let quantity = 1;
let shoppingList = reactive([]);
// Add item to the list
function addItem() {
if (item.trim() && quantity > 0) {
shoppingList.push({ id: Date.now(), name: item.trim(), quantity });
item = '';
quantity = 1;
}
}
// Remove item by id
function removeItem(id) {
const index = shoppingList.findIndex(i => i.id === id);
if (index !== -1) shoppingList.splice(index, 1);
}
</script>
<style>
form {
margin-bottom: 1rem;
}
input, button {
padding: 0.5rem;
margin-right: 0.5rem;
}
ul {
list-style: none;
padding-left: 0;
}
li {
margin-bottom: 0.5rem;
}
button.remove {
margin-left: 1rem;
color: red;
cursor: pointer;
}
</style>
<form on:submit|preventDefault={addItem}>
<input
type="text"
placeholder="Item name"
bind:value={item}
required
/>
<input
type="number"
min="1"
bind:value={quantity}
required
/>
<button type="submit">Add</button>
</form>
{#if shoppingList.length > 0}
<ul>
{#each shoppingList as { id, name, quantity } (id)}
<li>
{name} - {quantity}
<button class="remove" on:click={() => removeItem(id)}>✕</button>
</li>
{/each}
</ul>
{:else}
<p>Your shopping list is empty.</p>
{/if}
Explanation:
- Reactive state:
item and quantity hold the current form input values. shoppingList is an array of items.
- addItem(): Adds a new item with a unique
id (using Date.now()), name, and quantity to the list.
- removeItem(id): Removes an item by its
id.
- The form uses
on:submit|preventDefault to handle submission without page reload.
- The list is displayed with an
each block, showing item name, quantity, and a remove button.
- Basic styling for clarity.
You can copy-paste this into a .svelte file and it will work with Svelte 5. Let me know if you want it extended with features like editing or persistence!