Last active
July 6, 2017 00:22
-
-
Save jossmac/4e69a34101050b6b38b88af013b75aa5 to your computer and use it in GitHub Desktop.
A higher order component to replace pseudo-states when working with a CSS in JS solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
export default function withPseudoState(WrappedComponent) { | |
return class ComponentWithPseudoState extends Component { | |
actionKeys = ['Enter', ' '] | |
state = { | |
isActive: false, | |
isFocus: false, | |
isHover: false, | |
} | |
handleBlur = () => this.setState({ isFocus: false }); | |
handleFocus = () => this.setState({ isFocus: true }) | |
handleMouseOut = () => this.setState({ isActive: false, isHover: false }); | |
handleMouseOver = () => this.setState({ isHover: true }); | |
handleMouseUp = () => this.setState({ isActive: false }); | |
handleMouseDown = () => this.setState({ isActive: true }); | |
handleKeyDown = (event) => { | |
if (this.actionKeys.includes(event.key)) { | |
this.setState({ isActive: true }); | |
} | |
} | |
handleKeyUp = (event) => { | |
if (this.actionKeys.includes(event.key)) { | |
this.setState({ isActive: false }); | |
} | |
} | |
render() { | |
return ( | |
<WrappedComponent | |
onBlur={this.handleBlur} | |
onFocus={this.handleFocus} | |
onMouseLeave={this.handleMouseOut} | |
onMouseEnter={this.handleMouseOver} | |
onMouseUp={this.handleMouseUp} | |
onMouseDown={this.handleMouseDown} | |
onKeyDown={this.handleKeyDown} | |
onKeyUp={this.handleKeyUp} | |
{...this.state} | |
{...this.props} | |
/> | |
); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use like: