Search code examples
reactjstooltipchakra-uiellipsis

How can I show tooltip ONLY when ellipsis is activated?


I am using Chakra UI (Tooltip and the ellipsis) I have added the Tooltip to show the label on the title completely but I ONLY want to show the Tooltip when ellipsis is activated!

For example, in normal situation I do not want the Tooltip component on the text but only when there is ellipsis.

I appreciate your help, thank you

<Tooltip label="this is an example for a long text">
    <Text
     style={{
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
        }}
        >
    this is an example for a long text
        </Text>
        </Tooltip>

Solution

  • I have created my own component named CustomTooltip.

    export const CustomTooltip = ({
    ariaLabel,
    label,
    children,
    styles,
    placement,
    }: CustomTooltipProps) => {
    
    const ref = useRef<HTMLParagraphElement>(null)
    const [isOverflown, setIsOverflown] = useState(false)
    
    const compareSize = () => {
        const node = ref.current!
        setIsOverflown(node.scrollWidth > node.clientWidth)
    }
    
    useEffect(() => {
        compareSize()
        window.addEventListener('resize', compareSize)
    
        return () => {
            window.removeEventListener('resize', compareSize)
        }
    }, [])
    
    return (
        <Tooltip
            aria-label={ariaLabel}
            label={label}
            placement={placement}
            isDisabled={!isOverflown}
        >
            <Text sx={styles} ref={ref} isTruncated>
                {children}
            </Text>
        </Tooltip>
    )
    

    }

    then I call it in another component.

    <CustomTooltip
        styles={{color:"#FFFFFF"}}
        label="this is a Tooltip"
        placement='bottom-start'
        aria-label="this is a Tooltip"
    
        >
        this is a Tooltip
    </CustomTooltip>