Build Fast, Accessible React Command Palettes with cmdk





Build Fast React Command Palettes with cmdk — Guide & Examples


Build Fast, Accessible React Command Palettes with cmdk

Practical guide: installation, keyboard navigation, searchable menus, examples, and advanced patterns for cmdk in React.

Overview: What cmdk is and when to use it

cmdk is a compact, keyboard-first command menu toolkit for React apps that helps you implement a searchable command palette (think: ⌘K menus) without pulling in heavy UI frameworks. Designed for speed and accessibility, it provides primitives that are unopinionated about styling and state management so you can wire commands, filters, and keyboard shortcuts with minimal fuss.

Use cmdk when your app benefits from fast, global navigation or command execution—searching pages, running quick actions, or connecting deep links. If you want a responsive, a11y-friendly command palette that integrates with your own design system, cmdk is a strong fit.

Below you’ll find concrete installation steps, core APIs, keyboard and accessibility patterns, and advanced techniques such as virtualization, async search, and routing integration. Examples are practical and copy-paste ready so you can get a working command menu in minutes.

Installation & setup: Getting cmdk into a React app

Install cmdk via npm or yarn. It’s a tiny, dependency-free package that plays well with React 17+ and modern bundlers:

npm install cmdk
# or
yarn add cmdk

After installation, create a small provider-centered component that toggles visibility on ⌘/Ctrl+K. The library exposes primitives (Menu, Input, Item, Group) that you compose to build the UI and wire keyboard events. You control styling and layout; cmdk focuses on semantics and keyboard behavior.

For a real quick start, check the official repo and examples: cmdk GitHub. If you’re following a tutorial, this write-up builds on the practical example at Building Command Menus with cmdk.

Core concepts & API: items, groups, filtering, and state

cmdk exposes a minimal API: the Menu root, Input to capture the search string, Item for selectable actions, and Group and Separator for organization. Each Item can hold metadata (id, disabled, shortcut hints) and an onSelect handler. The primitives manage focus, active item, and keyboard wrapping so you can concentrate on commands.

Filtering is usually implemented outside cmdk: keep a stateful list of commands and compute visible items from the Input value. This separation keeps cmdk flexible and lets you implement fuzzy matching, async lookups, or categorized results as needed.

State patterns vary: local state for simple menus, React Context for app-wide command registries, or third-party state managers for complex apps. A common pattern is to register command descriptors (title, category, hotkey, handler) with a small registry; the command palette maps those descriptors to visible Items and calls handlers on selection.

Keyboard navigation & accessibility essentials

Keyboard-first operation is where cmdk shines. Out of the box, arrow keys move focus, Enter selects, and Esc closes the menu. Implementing a global toggle (⌘/Ctrl+K) usually involves a small window-level key listener that sets menuOpen state. Make sure you respect user platform keys: show ⌘K on macOS and Ctrl+K on Windows/Linux using simple user-agent or platform checks.

Accessibility requires proper aria attributes and focus management. cmdk handles much of the focus behavior but you still need to ensure input labeling, announce changes when results update, and provide clear skip/back-to-app behavior. For screen readers, make grouping sensible and avoid exposing raw internal IDs as labels.

Test keyboard flows thoroughly: landing focus on Input when opened, wrapping navigation, handling disabled items, and predictable Escape/blur behavior. Add visible keyboard shortcuts in the item hints so power users can learn time-saving keystrokes.

Example: Minimal searchable command menu

Here’s a compact pattern: maintain an array of command objects and filter them by the input value. Render matching commands as Items. Selecting a command calls its handler (navigate, run a function, open a modal).

// pseudo-code (JSX)

  
  
    {commands.filter(match(query)).map(cmd =>
       run(cmd)}>{cmd.title}
    )}
  

This pattern is intentionally simple and works well for small to medium command sets. For hundreds of commands you’ll want virtualization or server-side search to avoid rendering overhead and janky typing.

For a full, copyable demo, combine the snippet above with the registration pattern in your app root and integrate routing handlers to navigate via commands.

Advanced usage: performance, virtualization, async search, and integrations

Large command sets require tuning. Implementing virtualization (react-window or similar) prevents the DOM from ballooning. For async results—e.g., fuzzy search or remote suggestions—debounce input changes, show skeleton states, and cancel stale requests to avoid race conditions. cmdk itself is agnostic: it renders what you pass it, so offload heavy lifting to a search worker or server.

Integrate cmdk with routing by making commands mirror routes. Commands then call your router (React Router, Next.js router) on selection. You can also serialize command IDs into deep links so users can share “jump to” links for workflows, improving discoverability and automation.

Customization patterns include theming, icon and badge slots on Items, and multi-action rows (e.g., primary action plus secondary dropdown). Because cmdk is unstyled, you can apply your design tokens, animations, or micro-interactions without fighting a framework.

Troubleshooting, best practices, and common pitfalls

Common trap #1: blocking global keys. Window-level key listeners should be respectful: don’t hijack keys when form inputs are focused, and provide an option to disable the global shortcut. Common trap #2: expensive filtering on every keystroke. Debounce or move heavy operations off the main thread.

Keep command descriptors small and serializable. If you attach closures to the registry, ensure handlers remain stable or use refs to avoid unnecessary re-renders. For accessibility, verify that focus returns to the same logical place after the menu closes to preserve context.

Measure perceived speed: small animations and skeleton loaders can make async searches feel snappy even if the server response is slightly delayed. Provide clear empty-state messages and fallback commands when no results match, such as “Create new X” actions based on the query.

Integration patterns: routing, permissions, and telemetry

Map commands to routes by using route metadata to generate command descriptors. This makes the command palette a single source of truth for navigation. For permissioned apps, filter the registry per user role so commands only surface when allowed, and show helpful tooltips for locked commands.

Telemetry benefits: capture events for command opens, selections, and query terms to learn what users search for and where navigation gaps exist. Keep privacy in mind and avoid logging sensitive queries. Aggregated metrics help prioritize featured commands and improve search relevancy.

When using server-side rendering or static generation, hydrate the command registry on the client; avoid server-rendering ephemeral command state. Preserve UX consistency by ensuring the toggle key works after hydration completes.

Semantic core

  • Primary: cmdk, cmdk React, cmdk installation, cmdk setup, cmdk tutorial, cmdk example
  • Secondary: React command palette, React command menu, React ⌘K menu, React command menu component, React keyboard navigation, React searchable menu
  • Clarifying / Long-tail & LSI: React command palette library, cmdk getting started, cmdk advanced usage, React keyboard shortcuts, searchable command palette, command menu accessibility, cmdk virtualization, async search cmdk

Popular user questions (collected)

  • How do I install and set up cmdk in a React project?
  • How do I implement ⌘K / Ctrl+K global toggle for a command palette?
  • How do I add fuzzy or async search to a cmdk menu?
  • How do I make cmdk items accessible to screen readers?
  • How can I virtualize hundreds of command items in cmdk?
  • How to integrate cmdk with React Router or Next.js routing?
  • How do I add keyboard shortcuts hints to cmdk items?

FAQ

How do I install and initialize cmdk in a React app?

Install with npm or yarn (npm install cmdk). Import the primitives (Menu, Input, Item, Group) and render a small component that toggles open state on a global key press (⌘/Ctrl+K). Manage your command list in state and map it to Items. Make sure to focus the Input when the menu opens so keyboard users can type immediately.

How can I add fuzzy or async search to the command menu?

Perform filtering outside cmdk: debounce the Input value, then run a fuzzy match (fuse.js, flexsearch) or an async request. Display loading states while awaiting results, and cancel or ignore stale promises to prevent flicker. Render the results as Items; cmdk will handle selection and keyboard navigation.

What are best practices for keyboard navigation and accessibility?

Ensure the Input is focused on open, support arrow keys and Enter for selection, and respect Escape to close. Use semantic grouping and descriptive labels, expose shortcut hints (⌘/Ctrl) visually, and test with screen readers. Avoid trapping focus outside normal app behavior—return focus to the last element when the menu closes.


Further reading and official resources: cmdk GitHub, React documentation, and a practical tutorial at Building Command Menus with cmdk (dev.to).



Annunciate le date della prossima edizione di Eurochocolate: 13 – 22 Novembre 2026 La Fata Anastasia Cherednychenko testimonial della nuova campagna di comunicazione: Fate Dolci.

Sono stati in 1000, tra i tantissimi visitatori del primo sabato di Eurochocolate (15 novembre), a essere omaggiati con un lollipop a forma di stella da parte di un bellissima fata che soltanto oggi ha svelato la sua identità. Si tratta della cake designer Anastasia Cherednychenko, conosciuta sui social e non solo per il suo giovane brand torta mi via

Durante la conferenza stampa di presentazione del claim 2026, che si è svolta oggi presso il LAB – Luisa Annibale Base, Anastasia si è di nuovo presentata nelle vesti di Fata incantando i presenti con le sue dolci creazioni.

Prosegui la lettura


Al via domani la trentunesima edizione di Eurochocolate. Nel Centro Storico di Perugia fino al 23 Novembre.

Il programma del primo fine settimana.

Tanto buon cioccolato e imperdibili attività a tema si preparano ad accogliere i fedelissimi chocolover, con la trentunesima edizione di Eurochocolate che prenderà il via domani nel Centro Storico di Perugia, per proseguire fino al 23 novembre.

L’appuntamento con l’atteso press tour inaugurale è fissato per domani mattina, 14 novembre, alle ore 11, presso l’area Eurochocolate World in largo delle Libertà. Ad attendere i partecipanti i migliori produttori di cioccolato bean to bar e tree to bar a livello mondiale, per un totale di circa 40 marchi provenienti da ben 22 terre del cacao: Brasile, Colombia, Costa d’Avorio, Costa Rica, Ecuador, El Salvador, Filippine, Ghana, Hawaii, India, Indonesia, Jamaica, Madagascar, Messico, Nicaragua, Perù, Repubblica Dominicana, Thailandia, Trinidad e Tobago, Uganda, Venezuela, Vietnam.

Il programma di Eurochocolate quest’anno si intreccia inevitabilmente con l’imperdibile opportunità di visitare la Città del Cioccolato – il più grande museo esperienziale al mondo dedicato al Cibo degli Dèi – che lo scorso 1° novembre ha aperto al pubblico negli spazi dell’ex Mercato Coperto cittadino.

Prosegui la lettura


Eurochocolate 2025: “La festa tra le nuvole” è dal 14 al 23 novembre.

Presentato il programma di una ricchissima trentunesima edizione.

La trentunesima edizione di Eurochocolate è alle porte e punta molto in alto. Come già annunciato, “La festa tra le nuvole” è infatti il claim scelto quest’anno per accompagnare i chocolovers nel ricco programma di intrattenimento e approfondimento che, dal 14 al 23 novembre prossimi, animerà l’ormai popolarissimo Festival Internazionale del Cioccolato. Dieci intense giornate da vivere nel bellissimo centro storico di Perugia, alla scoperta di prelibatezze, luoghi e curiosità rigorosamente a tema, per scoprire giocosamente il Cibo degli Dèi in tutte le sue sorprendenti declinazioni sensoriali.

E il programma di Eurochocolate, da quest’anno, si intreccia inevitabilmente con l’imperdibile opportunità di visitare la Città del Cioccolato – il più grande museo esperienziale al mondo dedicato al Cibo degli Dèi – che lo scorso 1° novembre ha aperto le sue porte, sempre nel centro storico di Perugia e, precisamente, negli spazi dell’ex Mercato Coperto cittadino.

Si parte ovviamente dal gusto, con i nuovi prodotti firmati Costruttori di Dolcezze, protagonisti nell’originale Spazio Nuvola che verrà allestito nella centralissima piazza Matteotti.. Tra questi, la tavoletta con morbido ripieno Nugoloso, il lollipop Nuvola passeggera e il minibox finestrato Apriti cielo contenente squisiti dragée. Si aggiungono, la simpatica confezione di cioccolatini a forma di nuvole Cielo a pecorelle, cioccolato a catinelle e l’elegante Nuvoletta, entrambe realizzate in collaborazione con la maître chocolatier Alice Cianuri. Presso il vicino The Chocolate Bar, si potrà invece gustare il già apprezzatissimo Colpo di fulmine: il soffice dolce a forma di nuvola ideato dal noto designer Matteo. Safari can’t open the page? Best ways to fix Safari issues on Mac. Ragni che ne ha firmato l’originale stampo in silicone. A pochi passi, presso l’ex Borsa Merci di via Mazzini, il laboratorio didattico NuvoLab, appositamente pensato per coinvolgere bambini e famiglie, darà al pubblico la possibilità di realizzare live alcuni di questi iconici prodotti a tema.

Prosegui la lettura


Eurochocolate World porta in Italia il mondo del cioccolato bean to bar

Produttori d’eccellenza in arrivo da America Latina, Africa, Oceania e Asia

A poco meno di un mese dall’inizio del Festival Internazionale del Cioccolato, conosciamo più da vicino alcuni dei protagonisti di Eurochocolate World, l’area dedicata ai paesi della fascia equatoriale, questo’anno promossa da Sviluppumbria in collaborazione con Cacao Solution.

“Sviluppumbria, in qualità di soggetto di riferimento della Regione Umbria per la cooperazione internazionale e per il sostegno all’internazionalizzazione d’impresa – ha dichiarato l’Amministratore Unico di Sviluppumbria Luca Ferrucci – è lieta di sostenere questa iniziativa che apre Perugia e l’Umbria al mondo, ospitando i rappresentanti di tanti paesi produttori di cacao. Eventi come questo rappresentano un’importante occasione per mettere in contatto produttori e trasformatori, facilitando lo scambio di conoscenze, esperienze e opportunità commerciali in una filiera che unisce eccellenza, tradizione e sviluppo sostenibile. È anche un segnale forte e concreto dell’impegno dell’Umbria nella valorizzazione delle proprie filiere strategiche, come quella del cioccolato, e della capacità di attrarre e ospitare interlocutori di primo piano a livello internazionale”.

Prosegui la lettura


Eurochocolate 2025: “La festa tra le nuvole” è dal 14 al 23 Novembre

Più spazio a cioccolati insoliti e sostenibili: 22 paesi produttori di cacao protagonisti.

A volte sono bianche e corrono” scriveva Fabrizio De André con riferimento alle nuvole in un suo famoso testo. A Perugia sono di cioccolato e si sono date appuntamento nel bellissimo centro storico della città più dolce d’Italia dove, dal 14 al 23 novembre prossimi, si terrà la 31esima edizione di Eurochocolate. “La festa tra le nuvole” è infatti il claim scelto quest’anno per accompagnare i chocolovers nel ricco programma di intrattenimento e approfondimento che animerà l’ormai popolarissimo Festival Internazionale del Cioccolato. Dieci intense giornate alla scoperta di luoghi, memorie e visioni rigorosamente a tema. Una nuova dimensione onirica e golosa, dedicata a chi ha in testa dolci sogni, per vivere giocosamente il Cibo degli Dèi in tutte le sue sorprendenti declinazioni sensoriali.

Prosegui la lettura


Debutta la linea di prodotti firmata Costruttori di Dolcezze dedicata al claim “La Festa tra le Nuvole”

Puntuale come il cioccolato svizzero ma rigorosamente italiana, arriva, a fine estate, la linea di curiosi prodotti creati all’interno del giocoso laboratorio creativo di Costruttori di Dolcezze, l’inconfondibile marca leader nel mondo del funny chocolate.

Già a luglio, nella vetrina del nuovo The Chocolate Bar, si era affacciata la prima golosa proposta dedicata al claim di Eurochocolate 2025 “La Festa tra le Nuvole” ovvero il Colpo di fulmine: un soffice dolce a forma di nuvola che prende forma grazie a uno stampo in silicone appositamente ideato dal noto designer Matteo Ragni

Prosegui la lettura


Lunedì 7 Luglio 2025: Open Day del Cantiere Città del Cioccolato e Lancio del Countdown nella Giornata Mondiale dedicata al Cibo degli Dèi

Sarà una importante tappa di avvicinamento all’apertura della Città del Cioccolato quella programmata per il prossimo 7 luglio in occasione della Giornata Mondiale del Cioccolato quando, alle ore 16.30 presso l’ingresso delle scale mobili della Terrazza del Mercato Coperto, sarà svelato alla stampa e alle istituzioni locali il countdown che segnerà il tempo fino all’atteso taglio ufficiale del nastro di questo importante attrattore turistico-culturale della Città di Perugia.

Prosegui la lettura


hamburger-react: Build Animated Responsive Menus in React





hamburger-react: Build Animated Responsive Menus in React


hamburger-react: Build Animated Responsive Menus in React

Quick guide: installation, examples, customization, accessibility, and integration tips for hamburger-react in modern React apps.

Why use hamburger-react for React mobile navigation?

hamburger-react is a lightweight, animation-focused component library that provides polished hamburger icons and menu toggles for React apps. If you want an accessible, animated menu icon that integrates cleanly with state management and responsive navigation patterns, hamburger-react gives you prebuilt animations, sensible defaults, and props to control size, color, and behavior.

Using a dedicated component saves time versus crafting your own SVG/CSS animation from scratch. hamburger-react abstracts animation variants (Sling, Spin, Squash, etc.), controlled vs uncontrolled state, and label/aria attributes, which helps produce consistent UX across breakpoints.

This guide covers practical installation, a working example, customization strategies, accessibility considerations, and common integration patterns so you can ship a responsive React menu fast and reliably.

Quick start: installation and getting started

Install the package from npm or yarn. The library is small and installs as a regular dependency for both CRA and Vite projects. Below are the two common install commands — pick the one that matches your toolchain.

npm install hamburger-react
# or
yarn add hamburger-react

Once installed, import the variant you prefer (Sling, Spin, Squash, etc.) and wire it to React state. hamburger-react supports both controlled and uncontrolled usage. Controlled mode gives you programmatic control over the open/closed state; this is ideal when you need to toggle a navigation drawer or sync with other UI state.

Example controlled pattern: keep a boolean state in the parent, pass it to the component via the toggled prop, and supply the toggle setter. This allows you to render the menu or drawer conditionally, animate other elements, or integrate with routing.

Practical example: toggle a responsive mobile menu

Below is a compact, production-ready example using the controlled approach. The hamburger component controls a simple slide-down/slide-out navigation. This pattern keeps presentational concerns inside the toggle and places routing/navigation logic in the parent component.

import React, { useState } from 'react';
import { Sling as Hamburger } from 'hamburger-react'; // pick a variant

export default function MobileNav() {
  const [isOpen, setOpen] = useState(false);

  return (
    <header>
      <nav className="nav-bar">
        <div className="brand">MySite</div>
        <Hamburger toggled={isOpen} toggle={setOpen} size={24} color="#0b3b6f" label="Toggle menu" />
      </nav>

      {isOpen && (
        <div className="mobile-menu">
          <a href="/about">About</a>
          <a href="/work">Work</a>
          <a href="/contact">Contact</a>
        </div>
      )}
    </header>
  );
}

Key points in this example: the hamburger is controlled (toggled/toggle), accessible (label prop), and decoupled from the menu markup so you can plug any drawer implementation — CSS transitions, a slide-in component, or a portal-based overlay.

If you prefer uncontrolled usage, omit toggled and toggle. The component manages its internal state but is less flexible for coordinated animations or route-aware closing.

Customization, animations, and theming

hamburger-react ships with multiple animation variants and exposes props for size, color, and toggle label. Use these props to match your brand system without writing complex CSS. For deeper control you can wrap the component with styled-components or CSS modules and adapt spacing or hover states around the icon.

To customize animation timing or create a bespoke transition, pair hamburger-react with an animated container (e.g., framer-motion) or drive supplementary CSS transitions from the same state variable. Because the component only handles the icon, you retain complete control over how the navigation panel animates in and out.

For TypeScript projects, import types where necessary and declare the variant import. The props are simple, so TS integration is typically straightforward: maintain the boolean state type and the toggle setter as React.Dispatch<React.SetStateAction<boolean>>.

Accessibility, responsive behavior, and integration patterns

Accessibility is critical for navigation toggles. Use the label prop to provide a descriptive ARIA label (e.g., “Open main menu”). Ensure focus management: when the menu opens, move focus into the menu container; when it closes, return focus to the toggle. This pattern helps keyboard and assistive technology users navigate predictably.

On small screens, the hamburger often controls a drawer or overlay. Combine the icon’s state with a focus-trap library and aria-expanded attributes on the toggle to convey current state. If you render the menu conditionally, sync the toggle state with the presence of the menu to avoid content being hidden from screen readers inadvertently.

Integration patterns commonly include: toggling a CSS-driven slide panel, opening a portal-based modal for full-screen nav, or using the toggle state to switch a class on the body for scroll-lock behavior. Keep the icon semantics consistent and ensure your responsive breakpoints remove the hamburger when full navigation is available.

Troubleshooting, SSR, and performance tips

If you’re using server-side rendering, be mindful of hydrated mismatches: avoid rendering stateful UI that differs between server and client. Initialize toggled state to a deterministic value (usually false) so the initial markup matches. If you see a flicker, consider deferring client-only interactions until after hydration.

Performance impact is minimal — hamburger-react is tiny — but if you compose heavy animations around the icon, profile paint/layout costs on mobile. Use transform-based animations when possible to leverage the GPU and keep main-thread work low.

Common pitfalls: forgetting to pass the toggle setter in controlled mode, not providing a label prop, or attaching large DOM updates to the toggled state without smoothing transitions. Keep icon control separate from heavy logic (e.g., fetching data) to maintain responsive interaction.

Semantic core (keyword clusters)

Primary, secondary, and clarifying keyword clusters to use for SEO and content targeting — include these phrases naturally throughout templates, docs, and headings.

  • Primary (high intent):
    – hamburger-react, react hamburger menu, hamburger-react tutorial, hamburger-react installation, hamburger-react getting started
  • Secondary (how-to / features):
    – React animated menu icon, React mobile navigation, react responsive menu, react menu toggle, React navigation component, hamburger-react example, hamburger-react setup
  • Clarifying / LSI (variants & context):
    – hamburger-react customization, hamburger-react animations, react mobile menu, hamburger icon animation, npm hamburger-react, hamburger-react GitHub, accessible hamburger menu, hamburger-react typescript

Use these groups to craft headings, alt text, and anchor text. Example anchor text for backlinks: hamburger-react tutorial and hamburger-react npm.

FAQ

How do I install and get started with hamburger-react?

Install with npm install hamburger-react or yarn add hamburger-react. Import a variant (for example, Sling) and use controlled mode with a boolean state: pass the state as toggled and the setter as toggle. Controlled mode is recommended if you need to coordinate the icon with a drawer or route-aware menu.

How can I customize animations, size, and color?

hamburger-react exposes simple props such as size, color, and variants (Sling, Spin, Squash, etc.). For deeper styling, wrap the icon in a styled container or use CSS modules to adjust layout. Drive complementary animations (menu slide, overlay fade) from the same boolean state to keep transitions synchronized.

Is hamburger-react accessible and how do I handle focus?

Yes — pass a descriptive label prop (e.g., “Open main navigation”) so screen readers announce the control. When the menu opens, move focus into the menu (use a focus-trap) and restore focus to the toggle when closing. Also expose aria-expanded where appropriate to reflect the toggle state. These measures create predictable keyboard and assistive tech behavior.

If you want a deep-dive tutorial with variants and code examples, check the referenced walkthrough: hamburger-react tutorial.