jaywcjlove / react-hotkeys

React component to listen to keydown and keyup keyboard events, defining and dispatching keyboard shortcuts.

Home Page:https://jaywcjlove.github.io/react-hotkeys/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Include componentDidUpdate cycle to refresh the updated keysets

justinpark opened this issue · comments

Can you add the componentDidUpdate cycle to refresh the update keyset combination?

I think the following code block will fix the problem.

componentDidUpdate({ keyName: prevKeyName }) {
    Hotkeys.unbind(prevKeyName as string);
    const { filter } = this.props;
    if (filter) {
      Hotkeys.filter = filter;
    }
    Hotkeys(this.props.keyName as string, this.onKeyDown);
}

Is there another work around for this? When a component with HotKey updates the list of keyName dynamically, the new keyNames doesn't work

Solving this problem is not easy. I need some time.

A workaround I use is to use an HOC to force replace the whole <Hotkeys /> upon keyName update. Not ideal when the children render take heavy performance resource.

Demo code:

import React, { FC, ReactNode, useEffect, useState } from 'react'
import Hotkeys from 'react-hot-keys'

interface HotKeyHocProps {
  children: ReactNode
  keyName?: string
  onKeyUp?: (keyName: string, e: KeyboardEvent, handle: any) => void
  onKeyDown?: (keyName: string, e: KeyboardEvent, handle: any) => void
}

const HotKeyHoc: FC<HotKeyHocProps> = ({
  children,
  keyName,
  onKeyUp,
  onKeyDown,
}) => {
  const [tempUpdate, setTempUpdate] = useState(false)

  useEffect(() => {
    if (keyName && !tempUpdate) {
      setTempUpdate(true) // NOTE: Let conditional render statement remove the original <Hotkeys />
      setTimeout(() => setTempUpdate(false)) // NOTE: Re-render the whole <Hotkeys /> again after a short time
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [keyName])

  return keyName && !tempUpdate ? ( // NOTE: Setup the conditional render statement here
    <Hotkeys keyName={keyName} onKeyUp={onKeyUp} onKeyDown={onKeyDown}>
      {children}
    </Hotkeys>
  ) : (
    <>{children}</>
  )
}

export default HotKeyHoc

The issue should be resolved in the sourcecode pretty easily inside the code if you just implement ComponentDidUpdate...
for now if you guys looking for some fix( its a bit messy but doing the work)-
just add key property to the Hotkeys component with a random guid.
<Hotkeys keyName={keyName} onKeyUp={onKeyUp} onKeyDown={onKeyDown} key={Math.random()}> {children} </Hotkeys>