Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Search and Filtering | Working with Real Data
Introduction to Svelte

Search and Filtering

Свайпніть щоб показати меню

Modern frontend applications often allow users to search and filter data dynamically. Online stores, dashboards, social media platforms, and movie applications all rely heavily on filtering systems.

In this chapter, you will build a simple search feature using reactive state and dynamic rendering.

Creating Search State

Open App.svelte and add the following code:

<script>
  let search = "";

  let movies = [
    "Interstellar",
    "Inception",
    "Dune",
    "The Batman",
    "Oppenheimer"
  ];
</script>

The search variable stores the current search input value.

Binding the Search Input

Add an input field:

<input
  bind:value={search}
  placeholder="Search movies..."
/>

As the user types, the value of search updates automatically through two-way binding.

Filtering the Data

Create a filtered array using a reactive statement:

$: filteredMovies = movies.filter(movie =>
  movie.toLowerCase().includes(
    search.toLowerCase()
  )
);

The filter() method creates a new array containing only matching movies.

Whenever the search value changes, the filtered list updates automatically.

Rendering the Filtered Results

Display the filtered data:

<ul>
  {#each filteredMovies as movie}
    <li>{movie}</li>
  {/each}
</ul>

Now the interface updates dynamically as the user types into the search field.

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 5. Розділ 3

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 5. Розділ 3
some-alt