Cookie Consent by Free Privacy Policy Generator ๐Ÿ“Œ How to Build a Custom React Hook to Listen for Keyboard Events

๐Ÿ  Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeitrรคge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden รœberblick รผber die wichtigsten Aspekte der IT-Sicherheit in einer sich stรคndig verรคndernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch รผbersetzen, erst Englisch auswรคhlen dann wieder Deutsch!

Google Android Playstore Download Button fรผr Team IT Security



๐Ÿ“š How to Build a Custom React Hook to Listen for Keyboard Events


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

I recently built a neat little slide-out menu bar for an improved mobile viewing experience on my personal website.

Demonstration of Slide Out Menu Bar

This is a compressed gif; it is way smoother in action.

Part of my quest to make my work as accessible as possible includes navigating my site nicely using keyboard events. So, I decided to add a little keyboard shortcut to close my open menu when the Escape key is pressed.

Instead of jumping to a library that would implement this trivial change, I opted to build out this functionality myself, which gave me more control over exactly how it would work.

The end result is this simple useCloseMenuOnEscape hook that takes in values based on my isMenuOpen value and my toggleMenu function.

export function Navigation() {
  const { isMenuOpen, toggleMenu } = useLayoutStore();

  useCloseMenuOnEscape({ isMenuOpen, toggleMenu });

  return <>The part that is irrelevant to this post</>;
}

Under the Hook - Excuse the Pun

Let's dive into my useCloseMenuOnEscape hook:

import { useEffect } from "react";

interface UseCloseMenuOnEscapeArgs {
  isMenuOpen: boolean;
  toggleMenu: () => void;
}

export function useCloseMenuOnEscape({
  isMenuOpen,
  toggleMenu,
}: UseCloseMenuOnEscapeArgs) {
  useEffect(() => {
    if (!isMenuOpen) {
      return;
    }

    function keyDownHandler(e: globalThis.KeyboardEvent) {
      if (isMenuOpen && e.key === "Escape") {
        e.preventDefault();
        toggleMenu();
      }
    }

    document.addEventListener("keydown", keyDownHandler);

    return () => {
      document.removeEventListener("keydown", keyDownHandler);
    };
  }, [isMenuOpen]);
}

As you can see, it's actually all just a simple useEffect hook that does the following:

  1. It runs whenever the isMenuOpen prop changes.
  2. If the isMenuOpen prop is false, it doesn't do anything.
  3. If the isMenuOpen prop is true, it adds an event listener that will call the toggleMenu function if Escape is pressed.
  4. If the component that this hook is running on is unmounted, or the isMenuOpen prop changes, the event listener is removed.

This logic extraction to a custom hook is a great way to contain specific business logic in its own module. As you can see from my code snippet of the Navigation component above, it is much easier to read what is going on using this abstraction.

A More General Use Case Hook

My use case above was rather specific, but if you need to create a more generalized reusable hook, you could create this:

import { useEffect } from "react";

interface UseKeyboardShortcutArgs {
  key: string
  onKeyPressed: () => void;
}

export function useKeyboardShortcut({
  key,
  onKeyPressed
}: UseCloseMenuOnEscapeArgs) {
  useEffect(() => {
    function keyDownHandler(e: globalThis.KeyboardEvent) {
      if (e.key === key) {
        e.preventDefault();
        onKeyPressed();
      }
    }

    document.addEventListener("keydown", keyDownHandler);

    return () => {
      document.removeEventListener("keydown", keyDownHandler);
    };
  }, []);
}

In this scenario, you have a hook that you can use that accepts a key prop used to define what keyboard key you're listening for. It also accepts the onKeyPressed, which defines what will run if the specified key is pressed.

You can run this hook in your component like this:

function MyComponent() {
  useKeyboardShortcut({
    key: "Enter",
    onKeyPressed: () => console.log("Enter was pressed!"),
  })

  return <>whatever irrelevant thing you want to render</>
}

In this simple example, whenever MyComponent is mounted, an event listener is added that listens for the key Enter. Once Enter is pressed, it will run onKeyPressed, which in this case is a console log that prints out "Enter was pressed!".

Conclusion

I hope this post has given you insight into how you can create your own keyboard event listening hooks rather than jumping to a library.

Building your own solutions in this context gives you a finer grain of control over what you'd like to happen without adding another dependency to your project.

...



๐Ÿ“Œ How to Build a Custom React Hook to Listen for Keyboard Events


๐Ÿ“ˆ 71.39 Punkte

๐Ÿ“Œ Writing a Custom React useDebounce Hook with Typescript


๐Ÿ“ˆ 33.2 Punkte

๐Ÿ“Œ Writing a Custom useWindowSize React Hook


๐Ÿ“ˆ 33.2 Punkte

๐Ÿ“Œ Using Local Storage in React with Your Own Custom useLocalStorage Hook


๐Ÿ“ˆ 33.2 Punkte

๐Ÿ“Œ A Guide to Debouncing in JavaScript and React | Create a Customย Hook


๐Ÿ“ˆ 33.2 Punkte

๐Ÿ“Œ How to Create a Custom React Hook โ€“ a Hands-on Tutorial


๐Ÿ“ˆ 33.2 Punkte

๐Ÿ“Œ React Custom Hook: useDidMountEffect


๐Ÿ“ˆ 33.2 Punkte

๐Ÿ“Œ React Magic: How to Create a Custom Hook for Seamless Data Retrieval.


๐Ÿ“ˆ 33.2 Punkte

๐Ÿ“Œ Building a Simple React Custom Hook


๐Ÿ“ˆ 33.2 Punkte

๐Ÿ“Œ Fix the "React Hook is Called Conditionally" Error in React


๐Ÿ“ˆ 32.99 Punkte

๐Ÿ“Œ Building a CRUD App with Next.js, React Query, React Hook Form, and Yup


๐Ÿ“ˆ 32.99 Punkte

๐Ÿ“Œ This Week In React #130: Next.js, callback ref, Zod, Redux, React-Hook-Form, Redux, mdxjs-rs, Tamagui, Skia, Shopify, Solid...


๐Ÿ“ˆ 32.99 Punkte

๐Ÿ“Œ React Hook Form's Ritual: Elegant Forms in React


๐Ÿ“ˆ 32.99 Punkte

๐Ÿ“Œ Demystifying React Memoization: Understanding React.memo() and the useMemo hook


๐Ÿ“ˆ 32.99 Punkte

๐Ÿ“Œ Creating Dynamic Forms with React, Typescript, React Hook Form and Zod


๐Ÿ“ˆ 32.99 Punkte

๐Ÿ“Œ React 19, handling forms using useOptimistic and useFormStatus along with React Hook Form and Zod โ€ฆ practical example


๐Ÿ“ˆ 32.99 Punkte

๐Ÿ“Œ Crafting Forms in React: Vanilla vs. React Hook Form vs. Formik


๐Ÿ“ˆ 32.99 Punkte

๐Ÿ“Œ A counter that listen keyboard events ๐Ÿ•น๏ธ


๐Ÿ“ˆ 32.79 Punkte

๐Ÿ“Œ Hook into Netlifyโ€™s build events with Private Integrations


๐Ÿ“ˆ 31.71 Punkte

๐Ÿ“Œ Difference between Action Hook and Filter Hook in WordPress


๐Ÿ“ˆ 31.59 Punkte

๐Ÿ“Œ CVE-2024-1122 | Event Manager, Events Calendar, Events Tickets for WooCommerce Plugin Events Export authorization (ID 3033231)


๐Ÿ“ˆ 31.5 Punkte

๐Ÿ“Œ This Week In React #129: useEffectEvent, Storybook, OpenNEXT, React Email, Remix, Next.js, Pointer-Events, Expo-MDX...


๐Ÿ“ˆ 27.7 Punkte

๐Ÿ“Œ Listen Later: Listen to the Articles as Podcasts [Sponsor]


๐Ÿ“ˆ 26.79 Punkte

๐Ÿ“Œ How To Create Custom Alerts in React Using React-Notifications-Component


๐Ÿ“ˆ 26 Punkte

๐Ÿ“Œ This Week In React #127: Nextra, React-Query, React Documentary, Storybook, Remix, Tamagui, Solito, TC39, Rome...


๐Ÿ“ˆ 25.79 Punkte

๐Ÿ“Œ This Week In React #131: useReducer, Controlled Inputs, Async React, DevTools, React-Query, Storybook, Remix, RN , Expo...


๐Ÿ“ˆ 25.79 Punkte

๐Ÿ“Œ This Week In React #139: React.dev, Remix, Server Components, Error Boundary, Wakuwork, React-Native, Bottom Sheet...


๐Ÿ“ˆ 25.79 Punkte

๐Ÿ“Œ This Week In React #142: React-Query, Million, OpenNext, Ariakit, Expo-Image, React-Three-Fiber, TS 5.1, Node.js 20, WebGPU...


๐Ÿ“ˆ 25.79 Punkte

๐Ÿ“Œ This Week In React #146: Concurrency, Server Components, Next.js, React-Query, Remix, Expo Router, Skia, React-Native...


๐Ÿ“ˆ 25.79 Punkte

๐Ÿ“Œ Whatโ€™s New in React 19? React Canaries, Actions, and React Compiler


๐Ÿ“ˆ 25.79 Punkte











matomo