Skip to content

Commit da85375

Browse files
fix: improve how isOpen is handled
1 parent 768443a commit da85375

File tree

1 file changed

+28
-20
lines changed

1 file changed

+28
-20
lines changed

src/components/Tooltip/Tooltip.tsx

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -59,20 +59,37 @@ const Tooltip = ({
5959

6060
const handleShow = (value: boolean) => {
6161
setRendered(true)
62-
6362
/**
6463
* wait for the component to render and calculate position
6564
* before actually showing
6665
*/
6766
setTimeout(() => {
68-
if (setIsOpen) {
69-
setIsOpen(value)
70-
} else if (isOpen === undefined) {
67+
setIsOpen?.(value)
68+
if (isOpen === undefined) {
7169
setShow(value)
7270
}
7371
}, 10)
7472
}
7573

74+
/**
75+
* this replicates the effect from `handleShow()`
76+
* when `isOpen` is changed from outside
77+
*/
78+
useEffect(() => {
79+
if (isOpen === undefined) {
80+
return () => null
81+
}
82+
if (isOpen) {
83+
setRendered(true)
84+
}
85+
const timeout = setTimeout(() => {
86+
setShow(isOpen)
87+
}, 10)
88+
return () => {
89+
clearTimeout(timeout)
90+
}
91+
}, [isOpen])
92+
7693
useEffect(() => {
7794
if (show === wasShowing.current) {
7895
return
@@ -318,7 +335,11 @@ const Tooltip = ({
318335
})
319336
parentObserver.disconnect()
320337
}
321-
}, [anchorRefs, activeAnchor, closeOnEsc, anchorId, events, delayHide, delayShow])
338+
/**
339+
* rendered is also a dependency to ensure anchor observers are re-registered
340+
* since `tooltipRef` becomes stale after removing/adding the tooltip to the DOM
341+
*/
342+
}, [rendered, anchorRefs, activeAnchor, closeOnEsc, anchorId, events, delayHide, delayShow])
322343

323344
useEffect(() => {
324345
if (position) {
@@ -371,18 +392,7 @@ const Tooltip = ({
371392
return () => {
372393
mounted = false
373394
}
374-
}, [
375-
show,
376-
isOpen,
377-
anchorId,
378-
activeAnchor,
379-
content,
380-
html,
381-
place,
382-
offset,
383-
positionStrategy,
384-
position,
385-
])
395+
}, [show, anchorId, activeAnchor, content, html, place, offset, positionStrategy, position])
386396

387397
useEffect(() => {
388398
return () => {
@@ -396,9 +406,7 @@ const Tooltip = ({
396406
}, [])
397407

398408
const hasContentOrChildren = Boolean(html || content || children)
399-
const canShow = Boolean(
400-
hasContentOrChildren && (isOpen || show) && Object.keys(inlineStyles).length > 0,
401-
)
409+
const canShow = Boolean(hasContentOrChildren && show && Object.keys(inlineStyles).length > 0)
402410

403411
return rendered ? (
404412
<WrapperElement

0 commit comments

Comments
 (0)