ayrton / react-key-handler

React component to handle keyboard events :key:
http://ayrton.be/react-key-handler
388 stars 29 forks source link

Why is the HoC recommended? #140

Closed 0x80 closed 6 years ago

0x80 commented 6 years ago

According to the readme, HoC is recommended over component use. But I'm wondering why that is?

ayrton commented 6 years ago

You're really free to use whatever you prefer (and the README should reflect this), using the HOC is less lines of code, but gives you less flexibility

0x80 commented 6 years ago

OK clear. I think it is just a bit confusing if you don't elaborate on this, so personally I would remove it from the README because you probably do not want to discuss the pros and cons of different patterns in different situations.

I use it as a component. For example below I wrapped it in side a KeyPress component which can then be easily integrated into a button component. The disabled state of the button is passed down, so it disables the key trigger.

import * as React from "react";
import KeyHandler, { KEYPRESS } from "react-key-handler";

interface KeyPressProps {
  keyValue: string;
  disabled?: boolean;
  onKeyPress: () => void;
}

export default class KeyPress extends React.Component<KeyPressProps> {
  public render() {
    const { onKeyPress, keyValue, disabled } = this.props;

    return (
      <KeyHandler
        keyEventName={KEYPRESS}
        keyValue={keyValue}
        onKeyHandle={() => {
          if (!disabled) {
            this.props.onKeyPress();
          }
        }}
      />
    );
  }
}