Event Handling

Retend handles user interactions through event props.

Listening to Events

A function passed to an event prop registers a listener. Event names use camelCase, such as onClick, onInput, and onSubmit.

function LoggingButton() {
  const handleClick = () => {
    console.log('Button was clicked!');
  };

  return (
    <button type="button" onClick={handleClick}>
      Click Me
    </button>
  );
}

Working with the Event Object

The event handler receives the standard Event object, which contains information about the event, including its target and input details.

function SearchInput() {
  const handleInput = (event: Event) => {
    const target = event.target;
    if (target instanceof HTMLInputElement) {
      console.log('User typed:', target.value);
    }
  };

  return (
    <div>
      <label for="search">Search:</label>
      <input type="text" id="search" onInput={handleInput} />
    </div>
  );
}

Updating State from Events

The interface is updated in response to an event by calling .set() on the relevant Cell. Retend then updates the bound interface.

import { Cell } from 'retend';

function ToggleSwitch() {
  const isOn = Cell.source(false);

  const toggle = () => {
    isOn.set(!isOn.get());
  };

  return (
    <div>
      <p>Switch is: {isOn}</p>
      <button type="button" onClick={toggle}>
        Toggle
      </button>
    </div>
  );
}

Event Modifiers

Some event handlers need standard operations such as event.preventDefault(). For example, preventing the default action is commonly required when handling form submission.

Retend provides modifiers for these operations. Modifiers are appended to event names with double hyphens (--):

function Form() {
  const handleSubmit = () => {
    console.log('Form submitted!');
    // No need to call event.preventDefault() here!
  };

  return (
    <form onSubmit--prevent={handleSubmit}>
      <button type="submit">Submit</button>
    </form>
  );
}

Available Modifiers

  • --prevent: Automatically calls event.preventDefault(). Very common for forms and links.
  • --stop: Automatically calls event.stopPropagation(). Stops the event from triggering events on parent elements.
  • --once: Ensures the event handler only runs a single time, then automatically removes it.
  • --passive: Improves performance for scrolling events (like onScroll or onTouchMove). Cannot be used with --prevent.

Modifiers can be combined:

function EventShowcase() {
  const handleOnceClick = () => {
    console.log('Just once!');
  };

  return (
    <button type="button" onClick--stop--once={handleOnceClick}>
      One-Time Click
    </button>
  );
}