Last active
August 15, 2018 20:10
-
-
Save flushentitypacket/7e1ee0ecdb0b91aa510eb809e3e02ee8 to your computer and use it in GitHub Desktop.
Typescript React component to provide hover state.
This file contains hidden or 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 * as React from 'react' | |
type HoverProps = { | |
onMouseEnter: () => void, | |
onMouseLeave: () => void, | |
} | |
type ChildrenArgs = HoverProps & { | |
hoverProps: HoverProps, | |
isHover: boolean, | |
} | |
export type Props = { | |
children: (a: ChildrenArgs) => React.ReactNode, | |
} | |
type ComponentState = { | |
isHover: boolean, | |
} | |
export class HoverProvider extends React.PureComponent<Props, ComponentState> { | |
public state = { | |
isHover: false, | |
} | |
public render() { | |
const hoverProps = { | |
onMouseEnter: this.handleMouseEnter, | |
onMouseLeave: this.handleMouseLeave, | |
} | |
return this.props.children({ | |
...hoverProps, | |
hoverProps, | |
isHover: this.state.isHover, | |
}) | |
} | |
private handleMouseEnter = () => this.setState({isHover: true}) | |
private handleMouseLeave = () => this.setState({isHover: false}) | |
} |
This file contains hidden or 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 * as React from 'react' | |
import {HoverProvider} from './HoverProvider' | |
const SimpleExample: React.SFC = () => ( | |
<HoverProvider> | |
{({hoverProps, isHover}) => ( | |
<div {...hoverProps} style={{backgroundColor: isHover ? 'blue' : 'red'}} /> | |
)} | |
</HoverProvider> | |
) | |
const HoverAffectsOtherElement: React.SFC = () => ( | |
<HoverProvider> | |
{({hoverProps, isHover}) => ( | |
<div {...hoverProps}> | |
<div style={{backgroundColor: isHover ? 'blue' : 'red'}} /> | |
</div> | |
)} | |
</HoverProvider> | |
) | |
const HoverEnterAndLeaveOnDifferentElements: React.SFC = () => ( | |
<HoverProvider> | |
{({onMouseEnter, onMouseLeave, isHover}) => ( | |
<div onMouseLeave={onMouseLeave} style={{backgroundColor: isHover ? 'blue' : 'red'}}> | |
<div onMouseEnter={onMouseEnter}/> | |
</div> | |
)} | |
</HoverProvider> | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment