Skip to content
On this page

Chapter 4 - Adding Events To the Items Component

In this chapter we keep building our ItemsList.component.svelte so we can handle when the user clicks on an item in the list.

ItemsList Component

Start by adding a function called handleClick . This function will handle a click on each of the <li> elements and will toggle the item.selected property from true to false or vice versa. It will also logs the item id and selected properties to the console for preliminary debugging:

html
// file: src/components/items/ItemsList.component.svelte

<script lang="ts">
  // import a reference to our ItemInterace
  import type { ItemInterface } from '../../models/items/Item.interface'
  // expose a property called items with a default value of a blank array
  export let items: ItemInterface[] = []

  // item click handler
  const handleClick = (item: ItemInterface) => {
    item.selected = !item.selected
    console.log('handleItemClick', item.id, item.selected)
  }
</script>
...

And update the html by adding an on:click[1] attribute to the <li> element, pointing to our handler handleClick and passing a reference to the item as the argument:

html
// file: src/components/items/ItemsList.component.svelte

...

<div>
  <h3>My Items:</h3>
  <ul>
    {#each items as item}
      <li on:click={() => handleClick(item)}><!-- add on:click here -->
        {item.name}
      </li>
    {/each}
  </ul>
</div>

Note the syntax we use in the on:click attribute. We have an inline anonymous functoin here because we need to pass our item within handleClick.

typescript
on:click={ () => handleClick(item) }

If we did not have to pass data we could just simply do:

typescript
on:click={ handleClick }

Then, the web browser should have refreshed. Now, when clicking on the items in the list you should see the message being displayed in the browser console, and when clicking multiple times on the same item it should print true then false etc showing that toggling is working:

Now, we learned how to add a click handler to our component and changing the data item selected property that way. However, updating the selected property within the handleClick will not cause to re-render the html.

Let's verify this. Start by slightly modifying the text output by our list element, outputting also the selected value within [] (square brackets) like "[{item.selected}]":

html
// file: src/components/items/ItemsList.component.svelte

...
    {#each items as item}
      <li on:click={() => handleClick(item)}>
        {item.name} [{item.selected}] <!-- output selected next to the name -->
      </li>
    {/each}
...

Save and check the browser again. Notice that even though after clicking on the list items you see a message in the console with the updated value for the selected property, each item in the list always renders [false] next to the name.

Svelte is peculiar in this. In order to re-render our list, we need to update the items array by setting to itself[2]:

typescript
...
// item click handler
  function handleClick (item: ItemInterface) {
    item.selected = !item.selected
    items = items // add this line here to set items to itself to force a refresh
    console.log('handleItemClick', item.id, item.selected)
  }
...

Save once more and check the browser again. This time next to the name the value will change from [false] to [true] and viceversa:

In the next chapter we'll talk more in depth on how to better manage the application state using centralized place and a State Manager

Chapter 4 Recap

What We Learned

  • How to add a click handler to our ItemsList component
  • How to manipulate the item.selected property through our click handler

Observations

  • The items selected property is being manipulated directly within our component
  • We need a more centralized way to handle changes on the data and state of the application

Based on these observations, there are a few improvements that we will make in the next chapters:

Improvements

  • Implement a state manager to control our application state from a centralized place

  1. https://svelte.dev/tutorial/dom-events ↩︎

  2. https://svelte.dev/tutorial/updating-arrays-and-objects ↩︎

This is a sample from the book.