Skip to content

Instantly share code, notes, and snippets.

@beerose
Last active Sep 10, 2019
Embed
What would you like to do?
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