Last active
September 10, 2019 10:13
-
-
Save beerose/8afb17f5bfb25f01b5de7eda67d9888e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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