Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 26, 2022 11:08 am GMT

React: Overriding Browser's Keyboard Shortcuts

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;

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;

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;

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 :)


Original Link: https://dev.to/lico/react-overriding-browsers-keyboard-shortcuts-19bf

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To