Home > Back-end >  Run function on Ctrl K in React TypeScript application
Run function on Ctrl K in React TypeScript application

Time:10-11

I am working in a React TypeScript application (v18.2.0).

When the user presses Ctrl K I want to run a function.

The code I have within my component at the moment is:

const keyDownHandler = (event: KeyboardEvent) => {
  if (event.key === "k" && event.key === "Control") {
    console.log("You just pressed Control and K!");
  }
};

useEffect(() => {
  window.addEventListener("keydown", keyDownHandler);
});

However, TypeScript isn't happy. I get the error:

TS2367: This condition will always return 'false' since the types '"k"' and '"Control"' have no overlap.

Which I guess makes sense, since you can't have .key be k and Control at the same time. But then I'm stuck, I don't know how to check if both keys were pressed together.

Also, in Chrome, Ctrl K puts focus into the Chrome URL bar, how do I stop that from happening? I know they've done it on Tailwindcss docs.

CodePudding user response:

You should try:

const keyDownHandler = (event: KeyboardEvent) => {
  if (event.ctrlKey && event.key === "k") {
    console.log("You just pressed Control and K!");
  }
};

useEffect(() => {
  window.addEventListener("keydown", keyDownHandler);
});

ctrlKey can be different in different environment, so do try your code on both windows, and macos.

Docs: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/ctrlKey

  • Related