Skip to content

Commit

Permalink
Merge pull request #167 from element-hq/florianduros/memoize-tooltip
Browse files Browse the repository at this point in the history
Memoize cloned element in tooltip
  • Loading branch information
florianduros authored May 15, 2024
2 parents f4b03cb + 05e7e3d commit 197304c
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions src/components/Tooltip/Tooltip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import React, {
JSX,
isValidElement,
cloneElement,
useMemo,
} from "react";

import classNames from "classnames";
Expand Down Expand Up @@ -163,15 +164,22 @@ function TooltipAnchor({ children }: Readonly<PropsWithChildren>): JSX.Element {
const childrenRef = (children as unknown as { ref?: Ref<HTMLElement> })?.ref;
const ref = useMergeRefs([context.refs.setReference, childrenRef]);

if (!isValidElement(children)) {
// We need to check `isValidElement` to infer the type of `children`
const childrenProps = isValidElement(children) && children.props;

const element = useMemo(() => {
if (!isValidElement(children)) return;

const props = context.getReferenceProps({
ref,
...childrenProps,
});
return cloneElement(children, props);
}, [ref, children, childrenProps]);

if (!element) {
throw new Error("Tooltip anchor must be a single valid React element");
}

return cloneElement(
children,
context.getReferenceProps({
ref,
...children.props,
}),
);
return element;
}

0 comments on commit 197304c

Please sign in to comment.