DocsLearn

Events and forms

Events are attributes that start with on. A form field shows a value from state and changes it as it’s typed in.

In this lesson

  • how to respond to a click or a key;
  • how to keep a field in step with state;
  • how to work with switches, checkboxes and choices;
  • how to send a form.

Events

import { useState } from "react";
import { Button } from "@/components/ui/button";

export default function App() {
  const [said, setSaid] = useState("Nothing yet.");
  return (
    <div className="grid gap-3" onKeyDown={(e) => setSaid(`You pressed ${e.key}.`)} tabIndex={0}>
      <div className="flex gap-2">
        <Button onClick={() => setSaid("You clicked.")}>Click</Button>
        <Button variant="outline" onDoubleClick={() => setSaid("You double-clicked.")}>Double-click</Button>
      </div>
      <p className="text-sm text-muted-foreground">{said} (Focus here and press a key.)</p>
    </div>
  );
}

The handler gets the event: e.key, e.target, e.preventDefault(). Hand over a function, onClick={() => save()}, not its result: onClick={save()} would run it while drawing.

Fields that follow state

A field shows what state holds, and changes it as it’s typed in:

import { useState } from "react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

export default function App() {
  const [name, setName] = useState("");
  return (
    <div className="grid gap-2">
      <Label htmlFor="name">Your name</Label>
      <Input id="name" value={name} onChange={(e) => setName(e.target.value)} />
      <p className="text-sm text-muted-foreground">{name ? `Hello, ${name}.` : "Type your name."}</p>
    </div>
  );
}

Switches, checkboxes and choices

The components take checked and onCheckedChange, or value and onValueChange:

import { useState } from "react";
import { Switch } from "@/components/ui/switch";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";

export default function App() {
  const [email, setEmail] = useState(true);
  const [wrap, setWrap] = useState(false);
  const [plan, setPlan] = useState("monthly");
  return (
    <div className="grid gap-3">
      <Label className="flex items-center gap-2"><Switch checked={email} onCheckedChange={setEmail} /> Email me when it ships</Label>
      <Label className="flex items-center gap-2"><Checkbox checked={wrap} onCheckedChange={setWrap} /> Gift wrap</Label>
      <RadioGroup value={plan} onValueChange={setPlan}>
        <Label className="flex items-center gap-2"><RadioGroupItem value="monthly" /> Pay monthly</Label>
        <Label className="flex items-center gap-2"><RadioGroupItem value="yearly" /> Pay yearly</Label>
      </RadioGroup>
      <p className="text-sm text-muted-foreground">{email ? "Emailed" : "Not emailed"}, {wrap ? "wrapped" : "not wrapped"}, paid {plan}.</p>
    </div>
  );
}

Sending a form

onSubmit on the form takes Enter and the button alike. e.preventDefault() keeps the page where it is.

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";

export default function App() {
  const [email, setEmail] = useState("");
  const [sent, setSent] = useState("");
  const send = (e) => {
    e.preventDefault();
    setSent(`We'll write to ${email}.`);
  };
  return (
    <form className="grid gap-2" onSubmit={send}>
      <Input type="email" required aria-label="Email" placeholder="you@example.com" value={email} onChange={(e) => setEmail(e.target.value)} />
      <Button type="submit">Subscribe</Button>
      {sent && <p role="status" className="text-sm">{sent}</p>}
    </form>
  );
}

In an app, the form sends to the server with a "use server" function or the client: await sluurp.collection("subscribers").create({ email }).

Next: give components values and content from outside, in Props and children.

View as Markdown