PanelMenu: Make menu disappear on button press (#25015)

* Fix button press outside

* Add a prop to toggle button press

* Add comments

* Remove public
This commit is contained in:
Tobias Skarhed 2020-05-22 16:20:48 +02:00 committed by GitHub
parent 84031649e3
commit 5f4526ca64
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,7 +2,14 @@ import { PureComponent } from 'react';
import ReactDOM from 'react-dom';
export interface Props {
/**
* When clicking outside of current element
*/
onClick: () => void;
/**
* Runs the 'onClick' function when pressing a key outside of the current element. Defaults to true.
*/
includeButtonPress: boolean;
}
interface State {
@ -10,16 +17,26 @@ interface State {
}
export class ClickOutsideWrapper extends PureComponent<Props, State> {
static defaultProps = {
includeButtonPress: true,
};
state = {
hasEventListener: false,
};
componentDidMount() {
window.addEventListener('click', this.onOutsideClick, false);
if (this.props.includeButtonPress) {
// Use keyup since keydown already has an eventlistener on window
window.addEventListener('keyup', this.onOutsideClick, false);
}
}
componentWillUnmount() {
window.removeEventListener('click', this.onOutsideClick, false);
if (this.props.includeButtonPress) {
window.addEventListener('keyup', this.onOutsideClick, false);
}
}
onOutsideClick = (event: any) => {