Skip to content

Instantly share code, notes, and snippets.

@oprearocks
Last active March 27, 2017 21:37
Show Gist options
  • Save oprearocks/ff4260c48f660458de0cda7fbd5caf2d to your computer and use it in GitHub Desktop.
Save oprearocks/ff4260c48f660458de0cda7fbd5caf2d to your computer and use it in GitHub Desktop.
React.js Event Handlers Map
/**
* When writing event handlers it’s common to adopt the handle{eventName} naming convention.
*/
handleClick(e) { /* do something */ }
// For components that handle several event types, these function names can be repetitive. The names themselves might not provide much value, as they simply proxy to other actions/functions.
handleClick() { require("./actions/doStuff")(/* action stuff */) }
handleMouseEnter() { this.setState({ hovered: true }) }
handleMouseLeave() { this.setState({ hovered: false }) }
// Consider adding all handlers to a map and call them in one go
const handlers = {
click: () => require("./actions/doStuff")(/* action dates */),
mouseenter: () => this.setState({ hovered: true }),
mouseleave: () => this.setState({ hovered: false }),
default: () => console.warn("No handler available.")
};
handleEvent({type}) {
// Avoid mouseEnter, MouseLeave, Click
const NORMALIZED_TYPE = type.toLowerCase();
// If we have no registered handlers, we always use the 'default'
const HANDLER_TO_CALL = NORMALIZED_TYPE in handlers ? NORMALIZED_TYPE : 'default';
// No matter how many handlers we end up having in our `handlers` map, this code doesn't modify
// We also need to override the `this` binding to point to our component instead of the handlers hash.
handlers[HANDLER_TO_CALL].bind(this)();
}
//Alternatively, for simple components, you can call imported actions/functions directly from components, using arrow functions.
<div onClick={() => someImportedAction({ action: "DO_STUFF" })}
// Don’t fret about performance optimizations until you have problems. Seriously don’t.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment