DEV Community

Cover image for How to add HotKeys in React

How to add HotKeys in React

Chad Steele
I'm a Software Engineer with a BSEE and a master's in software engineering with loads of experience and 9 patents
Updated on ・1 min read

So, I was looking for this for longer than it took to write and so, I thought I'd better share it.


        <HotKey keys={["ArrowUp"]}>
           <SomeClickableComponent />
Enter fullscreen mode Exit fullscreen mode

Optional parameters [scope, callback]...

The default scope is the whole document and the default callback is to click the first child. Keep in mind, you can map more than one key, since keys attribute accepts a string or an array of strings. see

        <HotKey keys={["Enter","Space"]} scope={window.document} callback={myfunc}>
           <SomeClickableComponent />
Enter fullscreen mode Exit fullscreen mode

Here's the code...

import React from 'react'
import { useEffect } from 'react'

export function HotKey(props){

    const scope = props.scope || window.parent
        return ()=>{

    let keys = props.keys; // see
    if (!keys || !keys.length) return;
    if (typeof keys == 'string' || keys instanceof String) keys = [keys]

    const parent = React.createRef()
    const onKeydown = props.callback || ((e) => {
        if (keys.indexOf(e.code)>=0){

    return <div data-hotkey={props.keys} ref={parent}>


export default HotKey
Enter fullscreen mode Exit fullscreen mode



Discussion (1)

chadsteele profile image
Chad Steele Author

Looking forward to your feedback and suggestions