React component — OverflowDetectText
Apr 13, 2021
import React, { PropsWithChildren, useEffect, useRef, useState } from "react";import styled from "styled-components";const Text = styled.div`text-align: center;text-overflow: ellipsis;white-space: nowrap;overflow: hidden;max-width: 100%;`;interface Props {altText?: React.ReactElement;}const OverflowDetectText: React.FC<PropsWithChildren<Props>> = ({ children, altText, ...props }) => {const textRef = useRef<any>();const [isTextLong, setIsTextLong] = useState(false);useEffect(() => {if (textRef.current?.offsetWidth < textRef.current?.scrollWidth)setIsTextLong(true);}, [textRef.current?.offsetWidth, textRef.current?.scrollWidth]);return (<Text ref={textRef} {...props}>{isTextLong ? altText : children}</Text>);};export default OverflowDetectText;
This code was greatly inspired by the content of the link. https://codepen.io/triple-j/pen/wadKQB