Created
August 23, 2021 20:10
-
-
Save wiledal/d9b7e2c22427fb8d45f44d41ba90133e to your computer and use it in GitHub Desktop.
Simple 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 { useEffect, useRef } from "react"; | |
const UP = "ArrowUp"; | |
const DOWN = "ArrowDown"; | |
const LEFT = "ArrowLeft"; | |
const RIGHT = "ArrowRight"; | |
const B = "b"; | |
const A = "a"; | |
export const KONAMI_CODE = [UP, UP, DOWN, DOWN, LEFT, RIGHT, LEFT, RIGHT, B, A]; | |
const isBrowser = typeof window !== "undefined"; | |
export const useKonami = (callback?) => { | |
const index = useRef(0); | |
useEffect(() => { | |
const handleKeyDown = (event) => { | |
let currKey = KONAMI_CODE[index.current]; | |
if (event.key == currKey) { | |
index.current++; | |
} else { | |
index.current = 0; | |
} | |
if (index.current === KONAMI_CODE.length) { | |
index.current = 0; | |
console.log("k o n a m i"); | |
if (callback) callback(); | |
} | |
}; | |
if (isBrowser) window.addEventListener("keydown", handleKeyDown); | |
return () => { | |
if (isBrowser) window.removeEventListener("keydown", handleKeyDown); | |
}; | |
}, []); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment