Events

Event Handling

pushEvent from React reaches handle_event on the server

  • useLiveReact
  • pushEvent

Key concepts

useLiveReact() gives a component access to pushEvent without it being passed down as a prop. Calling it sends a message over the socket exactly as a phx-click or a form submit would.

Events.jsx
import React, { useState } from "react";
import { useLiveReact } from "live_react";

export function Events({ items }) {
  const { pushEvent } = useLiveReact();
  const [body, setBody] = useState("");

  const addItem = (e) => {
    e.preventDefault();
    if (!body.trim()) return;
    pushEvent("add_item", { body });
    setBody("");
  };

  return (
    <div className="flex flex-col gap-3">
      <form className="flex gap-2" onSubmit={addItem}>
        <input
          type="text"
          value={body}
          onChange={(e) => setBody(e.target.value)}
          placeholder="say something…"
          className="rounded-md border px-2 py-1"
        />
        <button type="submit" className="rounded-md border px-3 py-1">
          Add item
        </button>
      </form>

      <ul className="flex flex-col gap-1 text-sm">
        {items.map((item) => (
          <li key={item.id} className="border-t border-[#eee] py-1">
            {item.body}
          </li>
        ))}
      </ul>
    </div>
  );
}

How it works

Submitting the form calls pushEvent with the event name "add_item" and the typed text as its payload, which reaches handle_event("add_item", …) on the server. The server appends the item to its own items assign and reassigns it — LiveReact diffs the new list against the old one and only sends what changed.

The event name and payload are entirely up to the component; nothing about this is specific to lists or to this example. Any handle_event/3 clause the LiveView already has can be reached the same way.