shadcn.io is not affiliated with official shadcn/ui
Kbd examples · Platform Specific
Platform-Aware Shortcut Kbd for React
A shortcut that reads ⌘K on Apple devices and Ctrl K everywhere else.
A shortcut hint should show the keys the person actually has. This React example renders Ctrl K at first, then, once the component has mounted, tests the browser's user agent for Mac, iPhone, iPad or iPod and switches the first key to ⌘ when it matches. Both keys sit in a KbdGroup.
Preview
Installation
FAQ
How does the platform detection work?
After the component mounts, it tests navigator.userAgent against the pattern /Mac|iPhone|iPad|iPod/ and keeps the result in state. The first key shows ⌘ when it matches and Ctrl otherwise; the second is always K.
Why detect the platform after mounting?
A server render has no navigator, so the first render must not depend on it. Starting with Ctrl and switching after mount keeps the server HTML and the first client render the same; Mac users see Ctrl change to ⌘ right away.
What do other platforms see?
Windows, Linux, ChromeOS and Android all show Ctrl K, which is right for them: they use Ctrl for app shortcuts.
Is there a better way to detect the platform?
navigator.userAgentData.platform is cleaner where it exists, but not every browser has it, so the user agent is the fallback. The deprecated navigator.platform still works too. None is perfect: iPads can report a Mac user agent, which here gives the right answer.
Related
- Mac Command Symbol KbdThe Mac Command symbol and K grouped as
- Windows Key KbdThe Windows key and R grouped as the Win
- Mac Option Symbol KbdThe Mac Option symbol and Tab grouped as
- Command Palette Shortcut KbdThe ⌘K shortcut that opens a command
- Mac Control Symbol KbdThe Mac Control symbol and Space grouped
- Arrow Keys Cross Pattern KbdFour arrow keys in the inverted T of a