skip to Main Content

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>

2

Answers


  1. Chosen as BEST ANSWER

    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>
    

  2. You can see this answer: HTML text-overflow ellipsis detection

    function isEllipsisActive(element) {
         return (element.offsetWidth < element.scrollWidth);
    }
    

    Then, you can decide to show the Tooltip component based on the result of that function.

    const textRef = useRef()
    
    <Text ref={textRef}/>
    
    
    {isEllipsisActive(textRef) && (<Tooltip></Tooltip)}
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search