DEV Community

Cover image for How to add HotKeys in React
Chad Steele
Chad Steele

Posted on • Updated on

How to add HotKeys in React

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



Top comments (1)

chadsteele profile image
Chad Steele

Looking forward to your feedback and suggestions