Skip to content

Instantly share code, notes, and snippets.

@andrerfneves
Created September 17, 2018 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrerfneves/22927a799819bf21eca402ea5af79bc8 to your computer and use it in GitHub Desktop.
Save andrerfneves/22927a799819bf21eca402ea5af79bc8 to your computer and use it in GitHub Desktop.
ClickOutside React Component
// @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