Home > Enterprise >  Add a tooltip to MUI Badge content?
Add a tooltip to MUI Badge content?

Time:10-23

I want to add a tooltip to my MUI Badge component.

I tried wrapping the badge with a ToolTip component from MUI but tooltip text also displays when the children are hovered, I'd like it to only appear when the Badge itself is hovered.

I have also tried using the primitive title prop on the badge component but this has the same issue.

Does anyone know of a better way to add a tooltip to a Badge component?

my usage:

<Badge
      title={'Click to view more info'} // not ideal as the tooltip shows when the children are hovered too
      badgeContent={getTotalVulnerabilitiesCount()}
      showZero={false}
    >
        {children}
</Badge>

CodePudding user response:

I ended up building my own badge component, its not too long either so good solution imo. If anyone has feedback for the code please let me know :)

import React from 'react';
import { makeStyles, Tooltip } from '@material-ui/core';

const useStyles = makeStyles({
  badgeStyles: {
    minHeight: '24px',
    minWidth: '24px',
    position: 'absolute',
    top: '-12px',
    left: 'calc(100% - 12px)',
    color: 'white',
    borderRadius: '50%',
    backgroundColor: 'tomato',
    padding: '3px',
    fontSize: '.75rem'
  }
});

const Badge = props => {
  const {
    children,
    showZero,
    ...badgeContentProps
  } = props;

  return (
    <span>
      {children}
      {
        (showZero || props.badgeContent !== 0) && (
          <BadgeComponent {...badgeContentProps}/>
        )
      }
    </span>
  );
};

const BadgeComponent = props => {
  const classes = useStyles();

  const {
    badgeContent,
    badgeClasses,
    onClick,
    tooltipText,
    tooltipPlacement
  } = props;

  // If no tooltiptext provided render without Tooltip
  if(tooltipText == null) return (
    <span
      className = {`${badgeClasses ?? ''} ${classes.badgeStyles}`}
      onClick={onClick ? onClick : undefined}
    >
      {badgeContent}
    </span>
  );

  // Render with Tooltip
  return (
    <Tooltip title={tooltipText} placement={tooltipPlacement}>
      <span
        className = {`${badgeClasses} ${classes.notifyCount}`}
        onClick={onClick ? onClick : undefined}
      >
        {badgeContent}
      </span>
    </Tooltip>
  );
};

export default Badge;

CodePudding user response:

You're very close, badgeContent prop also accepts a ReactNode so you can put the Badge content inside a Tooltip without affecting the other component:

<Badge
  color="primary"
  badgeContent={
    <Tooltip title="Delete">
      <span>1</span>
    </Tooltip>
  }
>
  <MailIcon color="action" />
</Badge>

Codesandbox Demo

  • Related