Skip to content

Commit

Permalink
Manually watch for link, button clicks in tooltip
Browse files Browse the repository at this point in the history
  • Loading branch information
kylesuss committed Jun 17, 2019
1 parent 53e807a commit 87db8c9
Showing 1 changed file with 18 additions and 9 deletions.
27 changes: 18 additions & 9 deletions src/components/tooltip/WithTooltip.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useRef, useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import TooltipTrigger from 'react-popper-tooltip';
Expand Down Expand Up @@ -27,16 +27,24 @@ function WithTooltip({
startOpen,
...props
}) {
const tooltipWrapperRef = useRef(null);
const Container = svg ? TargetSvgContainer : TargetContainer;
const [isTooltipShown, setTooltipShown] = useState(startOpen);
const toggleTooltipShown = () => setTooltipShown(!isTooltipShown);
const closeTooltipOnClick = () => {
if (!closeOnClick) {
const closeTooltip = () => setTooltipShown(false);

useEffect(() => {
if (!tooltipWrapperRef.current || !closeOnClick) {
return;
}

setTooltipShown(false);
};
const clickableElements = tooltipWrapperRef.current.querySelectorAll('a, button');
clickableElements.forEach(element => element.addEventListener('click', closeTooltip));

// eslint-disable-next-line consistent-return
return () =>
clickableElements.forEach(element => element.removeEventListener('click', closeTooltip));
});

return (
<TooltipTrigger
Expand All @@ -58,12 +66,13 @@ function WithTooltip({
tooltipRef={tooltipRef}
arrowRef={arrowRef}
arrowProps={getArrowProps()}
onClick={closeTooltipOnClick}
{...getTooltipProps()}
>
{typeof tooltip === 'function'
? tooltip({ onHide: () => setTooltipShown(false) })
: tooltip}
<div ref={tooltipWrapperRef}>
{typeof tooltip === 'function'
? tooltip({ onHide: () => setTooltipShown(false) })
: tooltip}
</div>
</Tooltip>
)}
>
Expand Down

0 comments on commit 87db8c9

Please sign in to comment.