Search code examples
javascriptreactjstooltipmaterial-ui

Conditionally activate Material UI tooltip?


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.


Solution

  • 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.