Event Handling in Solid — SolidJS

A handler is written as a prop starting with on that holds a function: onClick={() => setCount(c => c - 1)}, onInput={e => setSearch(e.target.value)}. Don't…

The Order button on every book at Nadia's Bookshop just sits there until something listens for its click. That something is an event handler: a function that runs when the user does something, like clicking a button or typing in a box. In Solid's JSX, a handler is written as a prop starting with on on its element: onClick={...}, onInput={...}. If you come from React, this shape is familiar.

The interesting part is behind it. Nadia doesn't put a waiter at every button. She sits at the front desk, every click in the shop reaches her, then she checks which button was clicked and runs that button's note. That's onClick in Solid: one listener on document for every button. If you really want a waiter at the button itself, write on:click.

onClick: a handler as a prop

import { createSignal } from "solid-js"

function App() {
  const [count, setCount] = createSignal(0)

  return (
    <div>
      <button onClick={() => setCount(c => c + 1)}>+1</button>
      <button onClick={() => setCount(c => c - 1)}>-1</button>
      <p>Count: {count()}</p>
    </div>
  )
}
Event count() Paragraph
Page opens 0 Count: 0
Click +1 1 Count: 1
From the start, click -1 -1 Count: -1

The event object: e.target and e.currentTarget

A handler receives one argument, the event object (usually named e):

<input onInput={e => setSearch(e.target.value)} placeholder="Search title" />
<button onClick={e => console.log(e.target.tagName, e.currentTarget.tagName)}>
  <b>Order</b> The Rainbow Troops
</button>

Delegation: one listener on document

Nadia's Bookshop's book list, with an Order button on every book and a search box:

import { createSignal, For } from "solid-js"

const books = ["The Rainbow Troops", "This Earth of Mankind", "Beauty Is a Wound"]

function App() {
  const [ordered, setOrdered] = createSignal("-")
  const [search, setSearch] = createSignal("")

  function order(title, e) {
    console.log("order:", title, "| target:", e.target.tagName, "| currentTarget:", e.currentTarget.tagName)
    setOrdered(title)
  }

  return (
    <div>
      <input onInput={e => setSearch(e.target.value)} placeholder="Search title" />
      <p>Searching: {search()}</p>
      <For each={books}>
        {(title) => (
          <button onClick={(e) => order(title, e)}>
            <b>Order</b> {title}
          </button>
        )}
      </For>
      <p>Ordered: {ordered()}</p>
    </div>
  )
}

Solid's compiler doesn't add a listener to each button. It keeps the handler on its element (button.$$click = handler) and calls delegateEvents(["click", "input"]) once. The result, tested in Solid 1.9:

Written Listeners added
onClick on 3 buttons 1, on document
on:click on 3 buttons 3, one per button
onInput on the search box 1, on document
onChange on the search box 1, on the box itself

Three buttons, one listener. When you click Order on This Earth of Mankind, the click rises to document, Solid's listener walks up from the clicked element, finds the $$click on the This Earth of Mankind button, and runs it. Ordered: This Earth of Mankind. A thousand buttons would still be one listener.

Only common events that bubble are delegated: click, input, keydown, pointerdown, and the like. onChange, onFocus, onScroll are added straight to their element.

on:click: a listener right on the element

<button on:click={(e) => order(title, e)}> compiles to addEventListener("click", ...) on that button itself, not through document. The page looks the same, the difference is how it works: each element has its own listener. Use it when the event has to be handled on that element too, such as an element inside a closed Shadow DOM (mode: "closed"), a custom event with a special name, or when the order relative to other native listeners matters.

Data for a handler: the array form

<button onClick={[order, title]}>
  <b>Order</b> {title}
</button>

When onClick's value is an array [handler, data], Solid calls the handler with the data first and the event second: order(title, e), exactly like (e) => order(title, e) above. This form doesn't create a new function for each row, and it is still delegated.

onInput or onChange

onInput runs on every keystroke. onChange in Solid uses the browser's own change event, which on a text box only fires when the box is left or Enter is pressed. For a search box that follows typing, use onInput.

⚠️ Why a click does nothing, or throws

TL;DR: A handler is written as a prop starting with on that holds a function: onClick={() => setCount(c => c - 1)}, onInput={e => setSearch(e.target.value)}. Don't call it there: onClick={setCount(1)} runs during render and the next click throws. onClick is delegated: however many buttons there are, Solid adds one listener on document and looks for $$click from the clicked element upward. on:click uses addEventListener right on its element, one per element. e.target is the clicked element, e.currentTarget the handler's owner. onClick={[order, title]} calls order(title, e). For typing, onInput; onChange only fires when the box is left.

⚡ onClick: a handler as a prop

Write:

<button onClick={() => setCount(c => c + 1)}>+1</button>
<button onClick={() => setCount(c => c - 1)}>-1</button>
<p>Count: {count()}</p>

Meaning: The prop's name is on plus the event name: onClick, onInput. Its value is a function, which Solid calls later, when the button is clicked. Both buttons use the same signal, only the direction of the change differs.

This exercise looks for the button whose text is exactly -1, so - 1 isn't found.

⚡ Hand the function over, don't call it

Guess first: you write onClick={setCount(count() + 1)}. What happens?

The setter runs at once while the page is built, so the count is 1 straight away. The next click stops with TypeError: handler.call is not a function.

Meaning: Wrap it in a function: onClick={() => setCount(c => c + 1)}.

⚡ onClick is delegated, on:click is direct

Meaning: onClick on three buttons adds only one listener, on document. Solid looks for $$click from the clicked element upward. on:click uses addEventListener right on its element, one per element. Use it when the event has to be handled on that element too, for example when e.stopPropagation() on a button must stop its parent's listener.

What you will learn