Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React Hover Component Decorator
import React, { Component } from "react"
export default function hoverDecorator(InitialComponent) {
return class HoverDecorator extends Component {
constructor() {
super()
this.state = {
hover: false
}
}
handleMouseEnter() {
this.setState({ hover: true })
}
handleMouseLeave() {
this.setState({ hover: false })
}
render() {
return (
<InitialComponent
{...this.state}
onMouseEnter={this.handleMouseEnter.bind(this)}
onMouseLeave={this.handleMouseLeave.bind(this)}
{...this.props}
/>
)
}
}
}
@HoverDecorator class MyHeader extends Component {
render() {
const { hover } = this.props
const style = { background: hover ? "blue" : "red" }
return (
<h1 style={style}>
Hello World
</h1>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment