Reputation: 8577
I have the following React component using Material UI:
const MyButton = ({ warningText }) => (
<Tooltip title={warningText}>
<Button>Do action</Button>
</Tooltip>
)
Currently, this shows an empty tooltip when warningText
is undefined. Instead I would like to show no tooltip at all. Is there a way to conditionally surpress the tooltip in these cases?
Off course I could just use an if statement to not render the tooltip component, but this would lead to rather ugly code in my opinion.
Upvotes: 57
Views: 51970
Reputation: 59
You can use the disableHoverListener
prop, something like this:
<Tooltip
title={warningText}
disableHoverListener={!warningText}
>
<Button>Do action</Button>
</Tooltip>
https://mui.com/material-ui/api/tooltip/#Tooltip-prop-disableHoverListener
Upvotes: 5
Reputation: 2525
If you're looking to manually play around for customization, you can try to use the following solution:
As per the documentation, you can use the open
prop
and mouse events
to handle it manually.
In the following scenario, we will use state
to set showing the tooltip when we enter the mouse over the element
, and we will also use text &&
to assert that text
has a value, this will prevent the tooltip from showing when text
is undefined
.
const [showTooltip, setShowTooltip] = useState(false);
<Tooltip
open={text && showTooltip}
onMouseEnter={() => { setShowTooltip(true) }}
onMouseLeave={() => { setShowTooltip(false) }}
placement="top" title={text}
>
<div>
{text}
</div>
</Tooltip>
Note, the mui-tooltip is not a perfect component to begin with and is not very straight forward, this solution works for me but might not work in your situation as is, I will try to put it out, you can try to make it work on your end.
If it doesn't work for you, please leave a comment and I'll try to help.
Upvotes: -1
Reputation: 712
You should take a look at https://material-ui.com/api/tooltip/
There are options like
I think interactive={true}
should fit your needs best
<Tooltip title={warningText} interactive={!warningText}>...</Tooltip>
Upvotes: -4
Reputation: 37594
Should be
<Tooltip title={warningText == null ? "" : warningText}>
<Button>Do action</Button>
</Tooltip>
the docs say that it won't be displayed if the string length is zero.
https://material-ui.com/api/tooltip/
Tooltip title. Zero-length titles string are never displayed.
Upvotes: 127