Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Events

An event is the browser's notice about a user action: a click, typing, submitting a form. In Solid an event handler is passed with an attribute prefixed with on, as in React, but it receives the browser's real event object.

A click handler

// src/components/AddButton.jsx
export default function AddButton() {
  const handleClick = () => {
    console.log('Add a task');
  };
 
  return <button onClick={handleClick}>Add</button>;
}

After every click the browser console shows "Add a task". The function handleClick itself is passed, without parentheses: with them it would run once when the component is created.

The event object

The handler receives the event object. For an input field the text is in e.currentTarget.value:

// src/components/NewTodo.jsx
import { createSignal } from 'solid-js';
 
export default function NewTodo() {
  const [text, setText] = createSignal('');
 
  return (
    <div>
      <input onInput={(e) => setText(e.currentTarget.value)} />
      <p>You are typing: {text()}</p>
    </div>
  );
}

The paragraph under the field updates with every character you type. In Solid onChange behaves as in plain HTML — it fires only when the field loses focus, so typing letter by letter needs onInput.

Data for the handler

To pass a value to a handler, wrap the call in an arrow or pass an array of the function and the data:

// src/components/Priority.jsx
import { createSignal } from 'solid-js';
 
export default function Priority() {
  const [level, setLevel] = createSignal('normal');
 
  return (
    <div>
      <p>Priority: {level()}</p>
      <button onClick={() => setLevel('high')}>High</button>
      <button onClick={[setLevel, 'low']}>Low</button>
    </div>
  );
}

The [function, data] form calls the function with the data as the first argument and the event as the second. Both buttons change the paragraph text.

Delegation and on:

SyntaxHow it works
onClickSolid puts one listener on the document and finds the right element itself
on:clickA plain addEventListener right on the element

The first is cheaper for long lists. The second is for rare or custom events, and for cases where the bubbling order matters.

Common mistake

Calling the function instead of passing it:

// src/components/AddButton.jsx
export default function AddButton(props) {
  // Wrong: onClick={props.onAdd()} runs immediately on creation
  return <button onClick={() => props.onAdd()}>Add</button>;
}

onClick={props.onAdd()} runs the function once when the button is created and passes its result to onClick. Pass the function, or wrap the call in an arrow.

Thanks for reading!

Donate to the site — we work hard for you.