Skip to content

Instantly share code, notes, and snippets.

@beerose
Last active September 10, 2019 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beerose/8afb17f5bfb25f01b5de7eda67d9888e to your computer and use it in GitHub Desktop.
Save beerose/8afb17f5bfb25f01b5de7eda67d9888e to your computer and use it in GitHub Desktop.
export const Component: React.FunctionComponent<Props> = ({ text }) => {
const container = React.useRef() as React.MutableRefObject<HTMLDivElement>;
const [textContainerWidth, setTextContainerWidth] = React.useState(0);
React.useLayoutEffect(() => {
handleTextContainerWidth();
}, []);
React.useEffect(() => {
window.addEventListener('resize' handleTextContainerWidth);
return () => { window.removeEventListener('resize', handleTextContainerWidth) }
}, []);
const handleTextContainerWidth = () => {
if (container.current) {
setTextContainerWidth(container.current.scrollWidth);
}
};
// by default the arrow will be rendered
const shouldRenderArrow = () => {
const customText = document.getElementById('custom-info-text');
if (!customText) {
return true;
}
const { fontSize, fontFamily } = window.getComputedStyle(customText);
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
return true;
}
ctx.font = `${fontSize}px ${fontFamily}`;
const customTextWidth = ctx.measureText(text).width;
return customTextWidth > textContainerWidth - ARROW_WIDTH;
};
return (
<>
<div ref={container}>
<Text id="custom-info-text" color="black" textStyle="regular30">
{text}
</Text>
</div>
{shouldRenderArrow() && <Arrow />}
</>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment