Last active
May 12, 2024 18:36
-
-
Save kldzj/372820d2fbbcfa3fd32fe663c4f51d23 to your computer and use it in GitHub Desktop.
React Konami-Code Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useState, useEffect } from "react"; | |
| const code = "38384040373937396665"; | |
| export default function useKonami(func: () => void) { | |
| const [pattern, setPattern] = useState(""); | |
| useEffect(() => { | |
| const handler = (e: KeyboardEvent) => { | |
| if (!e.keyCode) return; | |
| if (e.repeat) return; | |
| setPattern((p) => (p + e.keyCode.toString()).slice(code.length * -1)); | |
| }; | |
| window.addEventListener("keyup", handler); | |
| return () => window.removeEventListener("keyup", handler); | |
| }, []); | |
| useEffect(() => { | |
| if (pattern === code) { | |
| if (func && typeof func === "function") func(); | |
| setPattern(""); | |
| } | |
| }, [pattern, func]); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment