Created
September 17, 2018 19:25
-
-
Save andrerfneves/22927a799819bf21eca402ea5af79bc8 to your computer and use it in GitHub Desktop.
ClickOutside React Component
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
// @flow | |
import React, { PureComponent } from 'react'; | |
type Props = { | |
onClickOutside: Function, | |
children: any, | |
}; | |
export default class ClickOutside extends PureComponent<Props> { | |
constructor(props: Props) { | |
super(props); | |
this.isTouch = false; | |
} | |
componentDidMount() { | |
document.addEventListener('touchend', this.handle, true); | |
document.addEventListener('click', this.handle, true); | |
} | |
componentWillUnmount() { | |
document.removeEventListener('touchend', this.handle, true); | |
document.removeEventListener('click', this.handle, true); | |
} | |
getContainer = (ref: any) => { | |
this.container = ref; | |
} | |
container: any; | |
isTouch: boolean; | |
handle = (e: Object) => { | |
if (e.type === 'touchend') this.isTouch = true; | |
if (e.type === 'click' && this.isTouch) return; | |
const { onClickOutside } = this.props; | |
const el = this.container; | |
if (!el.contains(e.target)) onClickOutside(e); | |
} | |
render() { | |
const { children, onClickOutside, ...props } = this.props; | |
return ( | |
<div | |
{...props} | |
ref={this.getContainer} | |
> | |
{children} | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment