Skip to content

Commit

Permalink
fix(tooltip): handle SSR in useTooltipInPortal (#1672)
Browse files Browse the repository at this point in the history
* fix SSR for useToolTipInPortal

* Apply suggestions from code review

---------

Co-authored-by: Chris Williams <williaster@users.noreply.github.com>
  • Loading branch information
korompaiistvan and williaster authored Mar 22, 2023
1 parent 1d5598c commit 590bbd2
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions packages/visx-tooltip/src/hooks/useTooltipInPortal.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useMemo } from 'react';
import React, { useEffect, useMemo, useState } from 'react';
import useMeasure, { RectReadOnly, Options as BaseUseMeasureOptions } from 'react-use-measure';

import Portal, { PortalProps } from '../Portal';
Expand Down Expand Up @@ -36,6 +36,11 @@ export default function useTooltipInPortal({
...useMeasureOptions
}: UseTooltipPortalOptions | undefined = {}): UseTooltipInPortal {
const [containerRef, containerBounds, forceRefreshBounds] = useMeasure(useMeasureOptions);
const [isSsr, setIsSsr] = useState(false);

useEffect(() => {
setIsSsr(false);
}, []);

const TooltipInPortal = useMemo(
() =>
Expand All @@ -50,16 +55,18 @@ export default function useTooltipInPortal({
const zIndex = zIndexProp == null ? zIndexOption : zIndexProp;
const TooltipComponent = detectBounds ? TooltipWithBounds : Tooltip;
// convert container coordinates to page coordinates
const portalLeft = containerLeft + (containerBounds.left || 0) + window.scrollX;
const portalTop = containerTop + (containerBounds.top || 0) + window.scrollY;
const scrollX = isSsr ? 0 : window.scrollX;
const scrollY = isSsr ? 0 : window.scrollY;
const portalLeft = containerLeft + (containerBounds.left || 0) + scrollX;
const portalTop = containerTop + (containerBounds.top || 0) + scrollY;

return (
<Portal zIndex={zIndex}>
<TooltipComponent left={portalLeft} top={portalTop} {...tooltipProps} />
</Portal>
);
},
[detectBoundsOption, zIndexOption, containerBounds.left, containerBounds.top],
[detectBoundsOption, zIndexOption, containerBounds.left, containerBounds.top, isSsr],
);

return {
Expand Down

0 comments on commit 590bbd2

Please sign in to comment.