Skip to content

Archive

Reactive Statement

1 articles
JavaScript 11 Sep 2025 2 min read

Building a Simple Search Feature in Svelte

Svelte’s reactivity makes it straightforward to update the UI when component state changes. In this example, we will build a small product search: as the user types, matching items appear immediately. 1. Complete Example Create src/routes/+page.svelte: <script lang="ts"> let query = ""; let products = ["Laptop", "Mouse", "Keyboard", "Monitor", "Printer"]; let results: string[] = []; function searchProducts(q: string) { if (q.trim() === "") { results = []; } else { results = products.filter((p) => p.toLowerCase().includes(q.toLowerCase()) ); } } // Reactive statement: runs whenever query changes $: searchProducts(query); </script> <input bind:value={query} placeholder="Search products..." /> <ul> {#if query.trim() !== ""} {#if results.length > 0} {#each results as item} <li>{item}</li> {/each} {:else} <li>No results</li> {/if} {/if} </ul> 2. How It Works The component has three pieces of state: