Skip to content

Commit 522ea20

Browse files
committed
Fix subtle issue when using the same menu several times
When pressing right click in another element while the menu was open, it wouldn't be displayed on the new component but would only hide the previous one.
1 parent b2b1539 commit 522ea20

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/ContextMenu.js

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import React from 'react';
2+
import ReactDOM from 'react-dom';
23
import PropTypes from 'prop-types';
34
import cx from 'classnames';
45
import assign from 'object-assign';
@@ -9,6 +10,15 @@ import SubMenu from './SubMenu';
910
import { hideMenu } from './actions';
1011
import { cssClasses, callIfExists, store } from './helpers';
1112

13+
/* This is a backward-compatible shim for React < 18 */
14+
function flushSync(callback) {
15+
if (ReactDOM.flushSync) {
16+
ReactDOM.flushSync(callback);
17+
} else {
18+
callback();
19+
}
20+
}
21+
1222
export default class ContextMenu extends AbstractMenu {
1323
static propTypes = {
1424
id: PropTypes.string.isRequired,
@@ -124,7 +134,11 @@ export default class ContextMenu extends AbstractMenu {
124134
handleHide = (e) => {
125135
if (this.state.isVisible && (!e.detail || !e.detail.id || e.detail.id === this.props.id)) {
126136
this.unregisterHandlers();
127-
this.setState({ isVisible: false, selectedItem: null, forceSubMenuOpen: false });
137+
flushSync(() => {
138+
/* We rely on being able to read this state change in handleShow,
139+
* so let's force a synchronous update in React 18. */
140+
this.setState({ isVisible: false, selectedItem: null, forceSubMenuOpen: false });
141+
});
128142
callIfExists(this.props.onHide, e);
129143
}
130144
};

0 commit comments

Comments
 (0)