Events
Run code on clicks, typing, and other browser events with onClick and the other on-props.
Shared state gave two components one count. Something still has to change it. That something is an event, like a click.
Misconception: the browser must download every click handler before the page works. At build time, the compiler puts each handler in its own chunk. The code for a click loads the first time someone clicks.
This is true wherever the page renders: in the browser alone, or on a server.
Click the button in the figure twice. Then type a new name.
When does the code for a click load?
Press the clicked button twice. Then type a new name. Watch what loads, and when.
import { state } from '@markless/core'; export default function Greeter() @{ let name = state('Ada'); let count = state(0); <input value={name} onInput={(event) => name = event.currentTarget.value} /> (not loaded) <button onClick={() => count++}>{name} clicked {count}</button> (not loaded)}- ranRan your component once, to set up the page.
- noteNo click or typing code loaded yet.
Simplified. The same thing happens when the page is built in the browser and when it comes from a server. A real build can group some of this code together.
Notice that the first click loads the click code, and the second click reuses it. Typing loads its own code, on the first key press.
import { state } from '@markless/core';
export default function Greeter() @{
let name = state('Ada');
let count = state(0);
<form onSubmit={(event) => event.preventDefault()}>
<input value={name} onInput={(event) => name = event.currentTarget.value} />
<button type="button" onClick={() => count++}>{name} clicked {count}</button>
</form>
}
An event prop is on plus the browser event name. Case after on does not matter: onKeyDown and onKeydown both listen for keydown. Your handler gets the browser’s event object.
To run two handlers on one event, pass an array: onClick={[first, second]}. They run in the order you write them.
Want the technical version? See Lazy chunks.
Next: How does a handler reach the real <input> to focus it? Elements →
