React: Overriding Browser's Keyboard Shortcuts

SeongKuk Han - Mar 26 '22 - - Dev Community

Browsers have many shortcuts. How do I override these shortcuts?


import { useEffect } from "react";

function App() {
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.ctrlKey && e.key === "1") {
        alert("shortcut");
      }
    };
    window.addEventListener("keyup", handler);

    return () => {
      window.removeEventListener("keyup", handler);
    };
  }, []);

  return <div className="App">App</div>;
}

export default App;
Enter fullscreen mode Exit fullscreen mode

keypress doesn't work in complex shortcuts like ctrl + Key, so I used keyup.

This code will make an alert when you press the shortcut ctrl + 1. But it won't work because ctrl + 1 is a reserved key to move to the first tab.

In this case, you can ignore default shortcuts by using preventDefault in keydown.

import { useEffect } from "react";

function App() {
  useEffect(() => {
    const ctrl1 = (e: KeyboardEvent) => e.ctrlKey && e.key === "1";

    const handler = (e: KeyboardEvent) => {
      if (ctrl1(e)) {
        alert("shortcut");
      }
    };

    const ignore = (e: KeyboardEvent) => {
      if (ctrl1(e)) {
        e.preventDefault();
      }
    };

    window.addEventListener("keyup", handler);
    window.addEventListener("keydown", ignore);

    return () => {
      window.removeEventListener("keyup", handler);
      window.removeEventListener("keydown", ignore);
    };
  }, []);

  return <div className="App">App</div>;
}

export default App;
Enter fullscreen mode Exit fullscreen mode

When a key that you want to bound is pressed, call preventDefault. It will prevent to make a default action.

But it's not possible to override some keys like ctrl + R(Refresh).

And if you want, you can make this as a component.

import { useEffect } from "react";

const Ctrl1 = ({ onPress }: { onPress: VoidFunction }) => {
  useEffect(() => {
    const ctrl1 = (e: KeyboardEvent) => e.ctrlKey && e.key === "1";

    const handler = (e: KeyboardEvent) => {
      if (ctrl1(e)) onPress();
    };

    const ignore = (e: KeyboardEvent) => {
      if (ctrl1(e)) e.preventDefault();
    };

    window.addEventListener("keyup", handler);
    window.addEventListener("keydown", ignore);

    return () => {
      window.removeEventListener("keyup", handler);
      window.removeEventListener("keydown", ignore);
    };
  }, []);

  return null;
};

function App() {
  return (
    <div className="App">
      <Ctrl1 onPress={() => alert("pressed ctrl1")} />
      App
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

The logic is the same but I think it looks more like the React way.

That's it. Thanks for reading this post.
Good coding :)

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player