Skip to content

Instantly share code, notes, and snippets.

@jossmac
Last active July 6, 2017 00:22
Show Gist options
  • Save jossmac/4e69a34101050b6b38b88af013b75aa5 to your computer and use it in GitHub Desktop.
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
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}
/>
);
}
};
}
@jossmac
Copy link
Author

jossmac commented Jul 6, 2017

Use like:

const Button = ({ isActive, isFocus, isHover, ...rest }) => {
  // do things with pseudo state
  return (
    <button {...rest} />
  );
}

export default withPseudoState(Button);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment