ayrton / react-key-handler

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

Have the higer-order component accept an onKeyHandle parameter #54

Closed petejodo closed 1 year ago

petejodo commented 8 years ago

As of right now a component that gets wrapped by keyHandler has to expect keyValue, etc being passed down. That causes the component to be coupled with keyHandler if all you want to do is fire a callback that is on the props object. A way around this would be to allow an onKeyHandle parameter be passed to keyHandler that could look like (ownProps, keyValue, keyEventName) => void or something akin to that.

Just want to open the discussion of any pros/cons of this approach

Here's an example:

import React, { Component } from 'react';
import { keyHandler, KEYPRESS } from 'react-key-handler';

const CloseButton = ({ closeHandler }) => <button onClick={closeHandler}>Close</button>;

const CloseOnEnterKeyOrButton = keyHandler(
  { keyEventName: KEYPRESS, keyValue: 'enter' },
  ownProps => {
    if (ownProps.closeHandler) ownProps.closeHandler();
  }
)(CloseButton);

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = { isOpened: true };
  }
  render() {
    if (this.state.isOpened) {
      return (
        <div>
          Some stuff
          <CloseOnEnterKeyOrButton closeHandler={this.setState.bind(this, { isOpened: false })} />
        </div>
      );
    }
    return null;
  }
}

This 2nd parameter to keyHandler would only be fired when enter would be pressed

ayrton commented 8 years ago

This feels like this can be the same possible solution that @villesau would like (described in https://github.com/ayrton/react-key-handler/issues/4#issuecomment-233568602). As mentioned in that issue I'm open to improvements and more than happy to accept contributions

ayrton commented 8 years ago

Looks like I'm in need of this myself, I'll be working on a solution for this sometime soon 😊

petejodo commented 8 years ago

Awesome. I've been wanting to help out and work on this but I've been super busy (+ a little vacation). I've actually had this tab open since I opened this issue to remind myself about it haha