Skip to content

Commit ef042b9

Browse files
authored
Merge pull request #3909 from DamianMaslanka5/fix-search-multiple-modals
Fix showing two modals after pressing ctrl+k or / to open the search modal for the first time
2 parents 5486e80 + 8275e1a commit ef042b9

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

src/theme/SearchBar/index.js

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { useEffect } from 'react';
1717
import { getGoogleAnalyticsUserIdFromBrowserCookie } from '../../lib/google/google'
1818

1919
let DocSearchModal = null;
20+
let searchContainer = null;
2021

2122
function Hit({ hit, children }) {
2223
const handleClick = () => {
@@ -69,7 +70,6 @@ function DocSearch({ contextualSearch, externalUrlRegex, ...props }) {
6970
clickAnalytics: true,
7071
};
7172
const history = useHistory();
72-
const searchContainer = useRef(null);
7373
const searchButtonRef = useRef(null);
7474
const [isOpen, setIsOpen] = useState(false);
7575
const [initialQuery, setInitialQuery] = useState(undefined);
@@ -100,18 +100,26 @@ function DocSearch({ contextualSearch, externalUrlRegex, ...props }) {
100100

101101
const onOpen = useCallback(() => {
102102
importDocSearchModalIfNeeded().then(() => {
103-
searchContainer.current = document.createElement('div');
103+
// searchContainer is not null here when the modal is already open
104+
// this check is needed because ctrl + k shortcut was handled by another instance of SearchBar component
105+
if (searchContainer) {
106+
return;
107+
}
108+
109+
searchContainer = document.createElement('div');
104110
document.body.insertBefore(
105-
searchContainer.current,
111+
searchContainer,
106112
document.body.firstChild,
107113
);
114+
108115
setIsOpen(true);
109116
});
110117
}, [importDocSearchModalIfNeeded, setIsOpen]);
111118

112119
const onClose = useCallback(() => {
113120
setIsOpen(false);
114-
searchContainer.current?.remove();
121+
searchContainer?.remove();
122+
searchContainer = null;;
115123
}, [setIsOpen]);
116124

117125
const onInput = useCallback(
@@ -204,7 +212,7 @@ function DocSearch({ contextualSearch, externalUrlRegex, ...props }) {
204212

205213
{isOpen &&
206214
DocSearchModal &&
207-
searchContainer.current &&
215+
searchContainer &&
208216
createPortal(
209217
<DocSearchModal
210218
onClose={onClose}
@@ -223,7 +231,7 @@ function DocSearch({ contextualSearch, externalUrlRegex, ...props }) {
223231
placeholder={translations.placeholder}
224232
translations={translations.modal}
225233
/>,
226-
searchContainer.current,
234+
searchContainer,
227235
)}
228236
</>
229237
);

0 commit comments

Comments
 (0)