---
title: .on()
description: Tutorial — attach event listeners to elements inside your component with the .on() builder method.
order: 102
---

import { Preview } from "$lib/components/preview";

export const example = `import ilha from "ilha";
import { Button } from "areia";

export default ilha
  .state("count", 0)
  .on("[data-action=increase]@click", ({ state }) => {
    state.count(state.count() + 1);
  })
  .render(({ state }) => (
    <>
      <p>Count: {state.count()}</p>
      <Button variant="primary" data-action="increase">
        Increase
      </Button>
    </>
  ));
`

# On

Use the `.on()` method to attach event listeners to elements inside your component.
It takes a selector and an event name joined by `@`, and a callback that receives
the component context — giving you direct access to `state` and more.

```ts
.on("[selector]@eventName", callback)
```

The selector works like `document.querySelector` scoped to your component's rendered
output. This means you can target any attribute, class, or element — `[data-action=increase]`,
`.btn-submit`, `input` — without worrying about conflicts with the rest of the page.

Inside the callback, updating state is as simple as calling the state property as a
function with a new value. Ilha will re-render only what changed — so clicking the
button below updates the count without touching anything else in the DOM.

<Preview code={example} size="lg" />

## Similar concepts

- React: `onClick` and other event props
- Vue: `v-on` / `@click`
- Svelte: `onclick`, `onchange`...
