Skip to content

Commit

Permalink
fix(popup): handle click outside popup area to close the popup
Browse files Browse the repository at this point in the history
  • Loading branch information
ichim-david committed Aug 8, 2023
1 parent 4435c1f commit a6da52d
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions src/ui/Popup/Popup.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class Popup extends React.Component {

this.triggerRef = React.createRef();
this.popupRef = React.createRef();
this.handleClickOutside = this.handleClickOutside.bind(this);

this.state = {
isOpen: false,
Expand All @@ -48,13 +49,15 @@ class Popup extends React.Component {
...this.props.popperModifiers,
],
});
document.addEventListener('mousedown', this.handleClickOutside);
}

componentWillUnmount() {
this.popper && this.popper.destroy();
document.removeEventListener('mousedown', this.handleClickOutside);
}

componentWillUpdate(nextProps, nextState, nextContext) {
UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) {
const position = nextProps.position;
if (
position &&
Expand All @@ -66,6 +69,22 @@ class Popup extends React.Component {
}
}

handleClickOutside(event) {
if (
this.popupRef &&
!this.popupRef.current.contains(event.target) &&
!this.triggerRef.current.contains(event.target)
) {
if (this.state.isOpen) {
this.setState((state) => {
return {
isOpen: false,
};
});
}
}
}

togglePopup() {
this.setState(
(state) => {
Expand Down Expand Up @@ -98,7 +117,6 @@ class Popup extends React.Component {
<div className="popup-trigger" ref={this.triggerRef}>
{React.cloneElement(trigger, {
[onEvent]: this.togglePopup,
ref: this.triggerRef,
})}
</div>
)}
Expand Down

0 comments on commit a6da52d

Please sign in to comment.