Skip to content

Instantly share code, notes, and snippets.

@achadha235
Last active December 11, 2020 11:10
Show Gist options
  • Select an option

  • Save achadha235/fbe533c23a32a9a73db86526ddfa1e6f to your computer and use it in GitHub Desktop.

Select an option

Save achadha235/fbe533c23a32a9a73db86526ddfa1e6f to your computer and use it in GitHub Desktop.
Interactive React Component
/**
* InteractiveComponent - Easily trigger event handler binding
* to instance context with a customizable method naming convention
e.g.
class Foo extends InteractiveComponent {
onFooClickedHandler(event){
console.log('state', this.state)
}
render() {
// This handler will already be bound and we don't need
// a call to this.onFooClickedHandler.bind in the constructor
return <button onClick={this.onFooClickedHandler}/>
}
}
*/
import React from 'react';
export class InteractiveComponent extends React.Component {
constructor(props) {
super(props);
const prototype = this.__proto__;
const propNames = Object.getOwnPropertyNames(prototype);
const hasSpecialPropName = (propName) => {
const prefix = props.handlerPrefix || 'on';
const postfix = props.handlerPostfix || 'Handler';
return propName.length > prefix.length + postfix.length &&
propName.slice(0, prefix.length) === 'on' &&
propName.slice(propName.length - postfix.length);
};
for (let i = 0; i < propNames.length; i++) {
const propName = propNames[i];
if (typeof prototype[propName] === 'function' &&
hasSpecialPropName(propName)
) {
prototype[propName] = prototype[propName].bind(this);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment