Closed
Description
Both Popover (coming soon) and Colorpicker use the same kind of logic so it'd be nice to extract into a common component.
Something like:
export class KuiClickOutsideToClose extends Component {
constructor(props) {
super(props);
// Use this variable to differentiate between clicks on the element that should not cause the pop up
// to close, and external clicks that should cause the pop up to close.
this.didClickMyself = false;
}
onClickOutside = () => {
if (this.didClickMyself) {
this.didClickMyself = false;
return;
}
this.props.onClickOutside();
};
onClickRootElement = () => {
// This prevents clicking on the element from closing it, due to the event handler on the
// document object.
this.didClickMyself = true;
};
componentDidMount() {
// When the user clicks somewhere outside of the color picker, we will dismiss it.
document.addEventListener('click', this.onClickOutside);
}
componentWillUnmount() {
document.removeEventListener('click', this.onClickOutside);
}
render() {
const props = Object.assign({}, this.props.children.props, {
onClick: this.onClickRootElement,
});
return cloneElement(this.props.children, props);
}
}
with usage like:
<KuiClickOutsideToClose
onClickOutside={this.props.closePopover}
>
<div
className={ classes }
{ ...rest }
>
{button}
{body}
</div>
</KuiClickOutsideToClose>
cc @cjcenizal