Reactions
Toggle named emoji reactions with native checkbox values, live counts and change events.
pnpm dlx shadcn@latest add @haze/reactions---
import { cn } from "../../../lib/haze/utils";
interface Reaction { id: string; emoji: string; label: string; count?: number; selected?: boolean; }
interface Props {
id: string;
name?: string;
label?: string;
items?: Reaction[];
disabled?: boolean;
class?: string;
}
const { id, name = id, label = "Reactions", items = [{ id: "helpful", emoji: "👍", label: "Helpful", count: 12 }, { id: "love", emoji: "💛", label: "Love", count: 4, selected: true }, { id: "celebrate", emoji: "🎉", label: "Celebrate", count: 2 }], disabled, class: className } = Astro.props;
---
<fieldset data-haze-reactions disabled={disabled} class={cn("grid min-w-0 gap-2", className)}>
<legend class="mb-2 text-[0.8125rem]/5 font-medium text-muted-foreground">{label}</legend>
<div class="flex flex-wrap gap-1.5">
{items.map((item, index) => <label class="relative inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-full border border-frame bg-muted px-2.5 text-xs font-medium text-foreground transition-[border-color,background-color,scale] duration-150 ease-snappy hover:bg-accent active:scale-[0.97] active:duration-75 has-checked:border-border-strong has-checked:bg-accent has-focus-visible:outline-2 has-focus-visible:outline-offset-1 has-focus-visible:outline-ring has-disabled:cursor-not-allowed has-disabled:opacity-50">
<input type="checkbox" id={`${id}-${index}`} name={name} value={item.id} checked={item.selected} data-count={Math.max(0, Math.floor(item.count ?? 0))} data-label={item.label} class="peer sr-only" />
<span aria-hidden="true" class="text-base/5">{item.emoji}</span>
<span class="sr-only">{item.label}</span>
<span data-count-label aria-hidden="true" class="font-sans font-medium tabular-nums text-muted-foreground peer-checked:text-foreground">{Math.max(0, Math.floor(item.count ?? 0))}</span>
</label>)}
</div>
<p data-reaction-status role="status" class="sr-only"></p>
</fieldset>
<script>
const reduced = matchMedia("(prefers-reduced-motion: reduce)");
// Digit roll (NumberFlow behaviour): only characters that changed move, up when the value rises, down when it falls.
const roll = (el: HTMLElement, next: string, direction: number) => {
const before = Array.from(el.dataset.rolled ?? el.textContent ?? "");
el.dataset.rolled = next;
el.replaceChildren();
if (reduced.matches) { el.textContent = next; return; }
const easing = getComputedStyle(el).getPropertyValue("--ease-snappy").trim() || "ease";
const after = Array.from(next);
after.forEach((character, index) => {
const previous = before[before.length - after.length + index];
const column = document.createElement("span");
column.className = "relative inline-grid overflow-hidden align-bottom whitespace-pre";
const digit = document.createElement("span");
digit.textContent = character;
column.append(digit);
el.append(column);
if (previous === character) return;
const shift = /\p{Nd}/u.test(character) ? 100 : 30;
digit.animate([{ opacity: 0, translate: `0 ${direction * shift}%` }, { opacity: 1, translate: "0 0" }], { duration: 250, easing });
if (previous === undefined) return;
const ghost = document.createElement("span");
ghost.className = "absolute inset-0";
ghost.textContent = previous;
column.append(ghost);
const out = ghost.animate([{ opacity: 1, translate: "0 0" }, { opacity: 0, translate: `0 ${-direction * shift}%` }], { duration: 250, easing });
out.finished.then(() => ghost.remove(), () => ghost.remove());
});
};
function enhance(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const status = root.querySelector<HTMLElement>("[data-reaction-status]");
const inputs = Array.from(root.querySelectorAll<HTMLInputElement>("input[type=checkbox]"));
const update = (input: HTMLInputElement, announce: boolean) => {
const base = Number(input.dataset.count);
const count = Math.max(0, base + Number(input.checked) - Number(input.defaultChecked));
const chip = input.closest("label")!;
const countLabel = chip.querySelector<HTMLElement>("[data-count-label]")!;
if (announce) {
const previous = Number(countLabel.dataset.rolled ?? countLabel.textContent);
if (count !== previous) roll(countLabel, String(count), count > previous ? 1 : -1);
if (input.checked && !reduced.matches) {
chip.classList.remove("animate-pop");
void chip.offsetWidth;
chip.classList.add("animate-pop");
}
} else {
countLabel.replaceChildren(String(count));
countLabel.dataset.rolled = String(count);
}
input.setAttribute("aria-label", `${input.dataset.label}, ${count} ${count === 1 ? "reaction" : "reactions"}${input.checked ? ", including yours" : ""}`);
if (announce) {
if (status) status.textContent = `${input.checked ? "Added" : "Removed"} ${input.dataset.label}. ${count} ${count === 1 ? "reaction" : "reactions"}.`;
root.dispatchEvent(new CustomEvent("haze:reaction-change", { bubbles: true, detail: { id: input.value, selected: input.checked, count, value: inputs.filter((item) => item.checked).map((item) => item.value) } }));
}
};
inputs.forEach((input) => { input.closest("label")!.addEventListener("animationend", (event) => (event.currentTarget as HTMLElement).classList.remove("animate-pop")); update(input, false); input.addEventListener("change", () => update(input, true)); });
inputs[0]?.form?.addEventListener("reset", () => queueMicrotask(() => { inputs.forEach((input) => update(input, false)); if (status) status.textContent = "Reactions reset."; }));
root.setAttribute("data-enhanced", "");
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-reactions]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-reactions-listener")) {
document.documentElement.setAttribute("data-haze-reactions-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- People should acknowledge a post or update with more than one independent reaction.
- A form needs to submit selected reaction identifiers while displaying existing totals.
When not to use
- Use rating when the feedback is an ordered score.
- Use emoji-picker when people need to search a larger set of emoji.
Installation
Add the Haze registry to components.json once, then install Reactions with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/reactionsnpx shadcn@latest add @haze/reactionsyarn dlx shadcn@latest add @haze/reactionsbunx --bun shadcn@latest add @haze/reactionsFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique caller supplied prefix for the control and its associated content. |
| name | string | id | Name submitted by the native form control. |
| label | string | Reactions | Legend naming the reaction group. |
| items | { id: string; emoji: string; label: string; count?: number; selected?: boolean }[] | Helpful / Love / Celebrate | Reaction definitions; a supplied count includes the current user's initial selection. |
| disabled | boolean | false | Prevents user changes through the native disabled state. |
| class | string | – | Additional classes on this component's outer wrapper. |
Keyboard interactions
- Tab
- Focus the next reaction checkbox.
- Space
- Add or remove the focused reaction.
Accessibility
- Every pill retains a real checkbox, its visible label supplies an emoji independent name, and checked state stays available without JavaScript.
- Enhanced accessible names include totals and whether the current person reacted; a status region announces each toggle.
- Counts are adjusted relative to the initial checked state, so an already selected reaction does not gain another count on initialization.
- Selected identifiers submit under the shared name and haze:reaction-change exposes the complete selected set for persistence.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Reactions" with `npx shadcn@latest add @haze/reactions`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import Reactions from "@/components/haze/ui/reactions.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/reactions.md
Customize with real content
Adapt the Haze reactions ui for our product. Replace the demo values of these props with our real content: id, name, label, items, disabled, class. Keep the layout, the heading level rules and these accessibility details: Every pill retains a real checkbox, its visible label supplies an emoji independent name, and checked state stays available without JavaScript. Enhanced accessible names include totals and whether the current person reacted; a status region announces each toggle. Counts are adjusted relative to the initial checked state, so an already selected reaction does not gain another count on initialization. Selected identifiers submit under the shared name and haze:reaction-change exposes the complete selected set for persistence. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using reactions, check it fits: use it when people should acknowledge a post or update with more than one independent reaction.; a form needs to submit selected reaction identifiers while displaying existing totals.. Avoid it when use rating when the feedback is an ordered score.; use emoji-picker when people need to search a larger set of emoji.. Alternatives: @haze/rating, @haze/emoji-picker, @haze/toggle-group.
Dependencies
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.