CN

Adding shortcut navigation to Next.js App Router

Spice up your Next.js 14 App Router with snappy keyboard shortcuts. It's easier than you think!

Why bother with shortcuts?

Okay, let's be real. Keyboard shortcuts might not be the first thing on your mind when building a website. But hear me out – they're pretty darn cool. Don't believe me? Give it a try right here: hit [H] for Home, [P] for Posts, or [C] for Courses. Neat, huh?

Sure, it might seem like a small touch, but it's these little details that can make your app stand out. And if you're building something people use day in and day out? Those shortcuts could be a real time-saver for your power users.

Let's build this thing

We're going to use a nifty little library called react-hotkeys-hook. It does exactly what it says on the tin – gives us hooks for hotkeys. Let's get cracking!

First things first, let's install it:

Terminal
npm install react-hotkeys-hook

Now, let's whip up a component to handle our shortcuts:

components/hotkeys.js
'use client';
import { useHotkeys } from 'react-hotkeys-hook';
import { useRouter } from 'next/navigation';

export default function Hotkeys() {
  const router = useRouter();

  useHotkeys('h', () => router.push('/'), { enableOnFormTags: true });
  useHotkeys('p', () => router.push('/posts'), { enableOnFormTags: true });
  useHotkeys('c', () => router.push('/courses'), { enableOnFormTags: true });
  useHotkeys('l', () => router.push('/paths'), { enableOnFormTags: true });
  useHotkeys('a', () => router.push('/about'), { enableOnFormTags: true });

  return null;
}

Pretty straightforward, right? We're just telling our app to listen for certain key presses and navigate accordingly. The enableOnFormTags option means these shortcuts will work even when you're typing in a form – handy!

Putting it all together

Now, here's the kicker – you need to let your users know these shortcuts exist. Otherwise, it's like having a secret menu at a restaurant that nobody knows about. Tasty, but pointless.

Once you've spread the word, just pop this component into your root layout:

app/layout.js
import Hotkeys from "@/components/hotkeys";

export default function RootLayout({children}) {
  return (
    <html lang="en">
    <body>
      <Hotkeys />
      {children}
    </body>
    </html>
  );
}

And boom! You're done. Your Next.js app now has some slick keyboard navigation.

Wrapping up

This is just scratching the surface. You could get fancy with more complex shortcuts, add visual cues, or even let users customize their own shortcuts. The sky's the limit!

Remember, it's these little touches that can turn a good app into a great one. So go ahead, give your users' keyboards something to do!

Want to read more articles like that?

Sign up to get notified when I publish more.

No spam. One click unsubscribe.

Read More on Fado Code Camp