iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐜

How to implement "disabled" behavior for Ant Design Tooltips

に公開

Correction: Passing an empty string to title makes it act like disabled

  <Tooltip title="">
    {children}
  </Tooltip>

↓↓↓↓↓↓↓↓ Incorrect Article ↓↓↓↓↓↓↓↓↓↓↓↓↓

Conclusion

This is a hacky approach where passing '' to the trigger prop prevents the Tooltip from being displayed.

  <Tooltip trigger={disabled ? '' : 'hover'}>
    {children}
  </Tooltip>

↓ Something like this

import React from 'react'
import { Tooltip as AntTooltip, TooltipProps } from 'antd'

type Props = { disabled: boolean } & TooltipProps
const Tooltip: React.FC<Props> = ({ disabled, children, trigger, ...props }) => 
  <AntTooltip
    {...props}
    trigger={disabled ? '' : trigger}
  >
    {children}
  </AntTooltip>

Challenges

Tooltip lacks a disabled-like prop

I want to specify disabled like the Button component so that the tooltip is not displayed only under certain conditions!

However, looking at the Antd Tooltip API section, there is no such thing.

https://ant.design/components/tooltip/#API

The open prop is different

Since props like open are meant to display the tooltip when set to true, it's not possible to use them to ensure nothing is displayed regardless of the interaction under specific conditions.

Currently, it can be hacked using trigger

By taking advantage of the fact that passing '' to trigger prevents the Tooltip from appearing, it is possible to implement a workaround by creating a wrapper component like the one below... however.

Since this is a hacky approach, you need to consider that it might suddenly stop working with an antd update.

import React from 'react'
import { Tooltip as AntTooltip, TooltipProps } from 'antd'

type Props = { disabled: boolean } & TooltipProps
const Tooltip: React.FC<Props> = ({ disabled = false, children, trigger, ...props }) => 
  <AntTooltip
    {...props}
    trigger={disabled ? '' : trigger}
  >
    {children}
  </AntTooltip>

Discussion