Skip to content

Instantly share code, notes, and snippets.

@AprilArcus
Last active August 29, 2015 14:17
Show Gist options
  • Save AprilArcus/f96b15c937b673af3617 to your computer and use it in GitHub Desktop.
Save AprilArcus/f96b15c937b673af3617 to your computer and use it in GitHub Desktop.
// April Arcus 2015 Public Domain
// A higher order React component that will emulate CSS :hover, :active,
// and :focus pseudo selectors by decorating a component with appropriate
// listeners, tracking internal state, and passing it to the component
// argument as additional props.
// Somewhat like Radium, but will not interfere with the use of these
// same event listeners inside the decorated component.
// c.f. https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750
import React from 'react';
export default function(Component) {
// be sure to subclass our component argument's parent class
// in case it isn't React.Component (e.g. a PureComponent)
return class extends Object.getPrototypeOf(Component) {
constructor(props) {
super(props);
this.state = {
hover: false,
active: false,
focus: false
};
}
render() {
return <Component onMouseEnter = { () => this.setState({ hover: true }) }
onMouseLeave = { () => this.setState({ hover: false, active: false }) }
onMouseDown = { () => this.setState({ active: true }) }
onMouseUp = { () => this.setState({ active: false }) }
onFocus = { () => this.setState({ focus: true }) }
onBlur = { () => this.setState({ focus: false }) }
{...this.props} {...this.state} />
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment