Created
January 26, 2022 20:45
-
-
Save dhruvilp/4a9457dbf2da03b576f9bce098fb387a to your computer and use it in GitHub Desktop.
useKeyPress React Hook
This file contains 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 React from "react"; | |
import { useState, useEffect } from "react"; | |
// Usage | |
export default function App() { | |
// Call our hook for each key that we'd like to monitor | |
const happyPress = useKeyPress("h"); | |
const sadPress = useKeyPress("s"); | |
const robotPress = useKeyPress("r"); | |
const foxPress = useKeyPress("f"); | |
const enterPress = useKeyPress("Enter"); | |
return ( | |
<div> | |
<div>h, s, r, f</div> | |
<div> | |
{happyPress && "😊"} | |
{sadPress && "😢"} | |
{robotPress && "🤖"} | |
{foxPress && "🦊"} | |
{enterPress && "E"} | |
</div> | |
</div> | |
); | |
} | |
// Hook - Create a new file for useKeyPress hook | |
function useKeyPress(targetKey) { | |
// State for keeping track of whether key is pressed | |
const [keyPressed, setKeyPressed] = useState(false); | |
// If pressed key is our target key then set to true | |
function downHandler({ key }) { | |
if (key === targetKey) { | |
setKeyPressed(true); | |
} | |
} | |
// If released key is our target key then set to false | |
const upHandler = ({ key }) => { | |
if (key === targetKey) { | |
setKeyPressed(false); | |
} | |
}; | |
// Add event listeners | |
useEffect(() => { | |
window.addEventListener("keydown", downHandler); | |
window.addEventListener("keyup", upHandler); | |
// Remove event listeners on cleanup | |
return () => { | |
window.removeEventListener("keydown", downHandler); | |
window.removeEventListener("keyup", upHandler); | |
}; | |
}, []); // Empty array ensures that effect is only run on mount and unmount | |
return keyPressed; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment