最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I get onKeyDown event to work in Next.jsReact - Stack Overflow

programmeradmin2浏览0评论

I'm building a website using Next.js, and currently I'm trying to get a simple function to run when pressing a key. The problem I'm having is that the onKeyDown event isn't being triggered like I expected. My code is as follows: <main onKeyDown={e => console.log("Key pressed")}>

Currently it's placed in the "main" element, which is the top root element of this ponent. I've tried placing the onKeyDown event in many of the other elements as well, without luck. I'm not sure if it's the placement which causes issues or my lack of understanding of how to use this event. Any help would be appreciated.

As for now I simply want it to write something in the console so that I can see that it triggers. I've tried using onKeyPress instead, as well as assigning a function to the event instead of a lambda expression, which shouldn't make a difference.

I'm building a website using Next.js, and currently I'm trying to get a simple function to run when pressing a key. The problem I'm having is that the onKeyDown event isn't being triggered like I expected. My code is as follows: <main onKeyDown={e => console.log("Key pressed")}>

Currently it's placed in the "main" element, which is the top root element of this ponent. I've tried placing the onKeyDown event in many of the other elements as well, without luck. I'm not sure if it's the placement which causes issues or my lack of understanding of how to use this event. Any help would be appreciated.

As for now I simply want it to write something in the console so that I can see that it triggers. I've tried using onKeyPress instead, as well as assigning a function to the event instead of a lambda expression, which shouldn't make a difference.

Share Improve this question asked Mar 24, 2022 at 13:19 NoobsterNoobster 1882 silver badges10 bronze badges 3
  • 1 You may need to put the event listener on window or document if you're trying to capture all key down events on the page. Unless you can focus "main" somehow, I'm not sure it will capture that event type. – tarrball Commented Mar 24, 2022 at 13:27
  • 1 @tarrball Well my initial approach was this: globalThis.addEventListener("keydown", e => { // do stuff }) But I quickly found out this made it trigger from all pages on the website. But thanks, I'll see if I can get something like that to work. – Noobster Commented Mar 24, 2022 at 13:31
  • 1 I got it to work by simply setting tabIndex attribute of <main> to -1: <main tabIndex={-1} onKeyDown={handleKeyDown}> Passing it a function handleKeyDown instead is unrelated. – Noobster Commented Mar 24, 2022 at 13:40
Add a ment  | 

1 Answer 1

Reset to default 8

In your ponent, use useEffect to add(and remove) the event listener to the document.

import { useEffect } from 'react'
// etc...

const Component = () => {

  useEffect(() => {
    const keyDownHandler = (e) => console.log(`You pressed ${e.code}.`);
    document.addEventListener("keydown", keyDownHandler);

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

  return <main>Press a key</main>;
};

You may even make a custom hook (beware of the dependency list):

import { useEffect } from 'react'
// etc...

const useKeyDown = (handler, deps = []) => {
  useEffect(() => {
    document.addEventListener("keydown", handler);
    // clean up
    return () => {
      document.removeEventListener("keydown", handler);
    };
  }, deps);
};

const Component = () => {
  useKeyDown((e) => console.log(`You pressed ${e.code}.`), []);
  return <main>Press a key</main>;
};
发布评论

评论列表(0)

  1. 暂无评论