Skip to content

Instantly share code, notes, and snippets.

@feimosi
Created November 28, 2018 18:28
Show Gist options
  • Save feimosi/b5ba525859a19ed13f397db747e6cfd3 to your computer and use it in GitHub Desktop.
Save feimosi/b5ba525859a19ed13f397db747e6cfd3 to your computer and use it in GitHub Desktop.
// @flow
import * as React from 'react';
import * as _ from 'lodash';
import BaseComponent from 'common/BaseComponent';
type Props = {
children: React.Node,
onMisclick: Function,
active?: boolean,
ignore?: Array<React.Node>,
};
export default class Misclick extends BaseComponent<Props> {
static defaultProps = {
onMisclick: () => null,
active: true,
ignore: [],
};
ref = null;
componentDidMount () {
window.addEventListener('click', this.handleWindowClick);
}
componentWillUnmount () {
window.removeEventListener('click', this.handleWindowClick);
}
handleWindowClick = (e: SyntheticInputEvent<HTMLElement>) => {
if (!this.props.active)
return;
if (this.ref === null)
return;
if (this.ref.contains(e.target))
return;
if (this.props.ignore.length > 0) {
const shouldIgnore = _.some(this.props.ignore, (elem) => elem instanceof Element && elem.contains(e.target));
if(shouldIgnore)
return;
}
this.props.onMisclick(e);
};
setRef = (ref: HTMLElement) => {
this.ref = ref;
};
render () {
return React.cloneElement(React.Children.only(this.props.children), {
ref: this.setRef,
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment