DEV Community

Gabe Ragland
Gabe Ragland

Posted on

How to create a useKonamiCode React hook ๐ŸŽฎ

This hook makes it easy to fire off a function when the visitor enters the Konami Code on their keyboard (โ†‘ โ†‘ โ†“ โ†“ โ† โ†’ โ† โ†’ B A). Every web app needs a cheat code right? Read through the code comments below to see how it works. Want to try it out? I'm using this hook in production on divjoy.com. Head over there, enter the code, and something amazing will happen. You won't regret it ๐Ÿ˜ป

import React, { useState, useEffect } from 'react';

// Usage
function App(){
  // Call hook with function to fire off  
  // after konami code is entered.
  useKonamiCode(() => {
    alert('Good job ๐Ÿฅณ');
  });

  // Render whatever you like
  return (
    <div>
      Can you find the easter egg?
    </div>
  );
}

function useKonamiCode(handler) {
  // State to hold array of recently pressed keys
  const [keys, setKeys] = useState([]);

  // Convert stored keys to string and match against konami code string
  const isKonamiCode = keys.join(' ') === 'up up down down left right left right B A';

  useEffect(() => {
    let timeout;

    // When a key is pressed
    window.document.onkeydown = (e) => {
      // Update array of keys in state with new key
      setKeys((currentKeys) => [...currentKeys, getKeyName(e.keyCode)]);

      // Clear 5s timeout since key was just pressed
      clearTimeout(timeout);

      // Reset keys if 5s passes so user can try again
      timeout = setTimeout(() => setKeys([]), 5000);
    };
  }, []);

  // Once konami code is entered call handler function
  // and reset keys so user can do it again.
  useEffect(() => {
    if (isKonamiCode) {
      handler();
      setKeys([]);
    }
  }, [isKonamiCode, handler]);

  return isKonamiCode;
}

const getKeyName = (keyCode) => {
  return {
    37: 'left',
    38: 'up',
    39: 'right',
    40: 'down',
    65: 'A',
    66: 'B',
  }[keyCode];
};
Enter fullscreen mode Exit fullscreen mode

Now you've got nothing stopping you from adding the Konami Code to your React app. If you do, be sure to share a link in the comments โคต๏ธ

Top comments (0)