wael zobani
wael zobani

Reputation: 31

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>

Upvotes: 0

Views: 1067

Answers (2)

wael zobani
wael zobani

Reputation: 31

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>

Upvotes: 3

Benedict Chen
Benedict Chen

Reputation: 31

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)}

Upvotes: 1

Related Questions