react-hotkeys icon indicating copy to clipboard operation
react-hotkeys copied to clipboard

Include componentDidUpdate cycle to refresh the updated keysets

Open justinpark opened this issue 6 years ago • 4 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);
}

justinpark avatar Oct 01 '19 23:10 justinpark

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

derekl-github avatar Oct 07 '19 19:10 derekl-github

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

jaywcjlove avatar Oct 08 '19 00:10 jaywcjlove

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


sailor95 avatar May 18 '21 17:05 sailor95

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>

tslilcrispel avatar May 10 '23 13:05 tslilcrispel