Have you ever wondered how to disable a tooltip in React Material UI after clicking on it? Let

I am working with a Material-UI tab component and I would like to include a tooltip feature.

The issue I am facing is that the tooltip does not disappear when I click on the tab. It should hide after clicking on the tab.

Currently, the tooltip remains visible even after I have clicked on the tab.

Is there a way to fix this behavior?

<Tabs
  className="navbar-routes"
  value={value}
  style={{ color: 'green'}}
  indicatorColor="secondary"
  onChange={handleChange} 
>
  {
    tabsData.map(({id,title,description}) => {
      return( 
        <ToolTip description={description}>
          <Tab
            style={{ 
              minWidth: 10,
              fontSize: '80%',
              fontWeight: 'bold',
              marginLeft: '-4px',
              marginRight: 4
            }} 
            key={id}
            component={Link}
            to={`/${title}`}
            label={`${title}`}
          />
        </ToolTip>
      );
    }
 )}
  </Tabs>

Answer №1

Upon reviewing the Material-UI tooltip API documentation

You will come across a property named disableHoverListener

bool
default: false
Prevents response to hover events.

Setting it as True will disable the tooltip trigger on onMouseOver event.


Update

https://i.sstatic.net/oJmbW.gif

Alternatively, you can take complete control of it by binding onClick, onMouseOver, onMouseLeave, open to the related component.

import React, { useState } from "react";
import "./styles.css";
import { Tooltip, Tab } from "@material-ui/core";

export default function App() {
  const [flg, setFlg] = useState(false);
  const [isHover, setIsHover] = useState(false);
  return (
    <div className="App">
      <Tooltip
        title={"message"}
        aria-label="add"
        placement="bottom"
        open={!flg && isHover}
      >
        <Tab
          label={`Click: ${!flg ? "enabled" : "disabled"}`}
          onClick={() => setFlg(!flg)}
          onMouseOver={() => setIsHover(true)}
          onMouseLeave={() => setIsHover(false)}
        />
      </Tooltip>
    </div>
  );
}

Give it a try online:

https://codesandbox.io/s/tender-frog-34ekm?fontsize=14&hidenavigation=1&theme=dark

Answer №2

I approached this problem by implementing a conditional rendering of tooltips. If you don't want the tooltip to show up for the tab corresponding to the currently active route, you can follow these steps:

function CustomTooltip({showTooltip, children, ...props}) {

    return showTooltip ? <Tooltip {...props}>{children}</Tooltip> : children;

}

function TabComponent() {
    const currentLocation = useLocation();

    return (
        <Tabs
          className="navbar-routes"
          value={value}
          style={{ color: 'green'}}
          indicatorColor="secondary"
          onChange={handleChange} 
        >
          {
            tabsData.map(({id,title,description}) => {
              return( 
                <CustomTooltip 
                    showTooltip={currentLocation.pathname.indexOf(title) === -1} /* Display tooltip only on inactive URLs */
                    title={description}
                >
                  <Tab
                    style={{ 
                      minWidth: 10,
                      fontSize: '80%',
                      fontWeight: 'bold',
                      marginLeft: '-4px',
                      marginRight: 4
                    }} 
                    key={id}
                    component={Link}
                    to={`/${title}`}
                    label={`${title}`}
                  />
                </CustomTooltip>
              );
            }
         )}
        </Tabs>
    )
}

Answer №3

You have the option to create a customizable tooltip with controlled state for opening and closing.

import Tooltip, { TooltipProps } from "@mui/material/Tooltip";
import { useState } from "react";

/**
 * MUI Tooltip wrapper that adjusts when focused is lost.
 */
export function ManagedTooltip(props: TooltipProps) {
    const [open, setOpen] = useState<boolean>(false);

    // Encapsulate Tooltip in div for handling mouse events
    return <div style={{ display: 'flex' }}
        onMouseEnter={() => setOpen(true)}
        onMouseLeave={() => setOpen(false)}
        onClick={() => setOpen(false)}
    >
        {/* Display original MUI Tooltip with added functionalities */}
        {/* Override open attribute for complete control, and disable internal listeners */}
        <Tooltip {...props} open={open} disableHoverListener disableFocusListener />
    </div>;
}

Once configured, you can easily incorporate it in any part of your application just like the standard MUI tooltip.

<Tabs
  className="navbar-routes"
  value={value}
  style={{ color: 'green'}}
  indicatorColor="secondary"
  onChange={handleChange} 
>
  {
    tabsData.map(({id,title,description}) => {
      return( 
        <ManagedTooltip description={description}>
          <Tab
            style={{ 
              minWidth: 10,
              fontSize: '80%',
              fontWeight: 'bold',
              marginLeft: '-4px',
              marginRight: 4
            }} 
            key={id}
            component={Link}
            to={`/${title}`}
            label={`${title}`}
          />
        </ManagedTooltip>
      );
    }
 )}
  </Tabs>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Grid element's height does not correspond to the responsive square child dimension

In my latest project, I am developing a web application using React and Material-ui. One of the challenges I have encountered is creating a responsive square div for a map component. Unfortunately, attempting to implement a solution from a trick on iamstev ...

Having issues with Facebook's login API for JavaScript?

Apologies for the improper formatting. I am encountering errors in my JavaScript compiler while working with the Facebook Login API... Error: Invalid App Id - Must be a number or numeric string representing the application id." all.js:53 "FB.getL ...

Ways to transfer information from a Redux state to a state in a React hook

I am facing a challenge in my react/redux app where I need to pass data from the state in redux to my react component's useState. I have attempted various solutions but nothing seems to work. Can anyone suggest an efficient way to tackle this issue us ...

Manipulating and transforming data through Puppeteer's iterative process into an object structure

As a beginner with the puppetteer library, I'm trying to iterate through Amazon reviews and save each comment as an object. Although my code seems to be functioning, it only retrieves the first comment and then stops. async function scrapeProduct(ur ...

Achieve seamless deployment of two React- JS applications on the same domain using Kubernetes. One application will be located in the root while the other will be in a designated path for efficient

For the past 3 days, I've been facing an issue with deploying two react-js applications in Kubernetes. One application is supposed to be deployed at , and the other at . Note: The URLs provided are just placeholders for illustration purposes. The fi ...

How to empty an array once all its elements have been displayed

My query pertains specifically to Angular/Typescript. I have an array containing elements that I am displaying on an HTML page, but the code is not finalized yet. Here is an excerpt: Typescript import { Component, Input, NgZone, OnInit } from '@angul ...

Is there a way to verify if all the values in an array of objects are identical?

In this scenario, my array consists of entries with identical address IDs but different phone types and numbers. I am in need of assistance with iterating through the array to extract the phone type and number when the address ID matches. I seem to encount ...

The distinction between a keypress event and a click event

Due to my eyesight challenges, I am focusing on keyboard events for this question. When I set up a click event handler for a button like this: $("#button").on("click", function() { alert("clicked"); }); Since using the mouse is not an option for me, ...

What are the reasons for the failure of parsing this specific Twitter JSON file using Angular $http, and how can I troubleshoot and resolve the issue

After finding a JSON example on the following website (located at the bottom): , I decided to save it to a file on my local system and attempt to retrieve it using Angular's $http service as shown below: To begin, I created a service: Services.Twitt ...

What is the best way to include a scrollbar in a modal window?

Does anyone know how to add a scroll function to my modal in CSS? I have too many elements and would like to implement a scrollbar. You can see what it looks like here: Any suggestions on how to add the right scrollbar? If you need to reference my CSS, y ...

Creating dynamic divs on button click for my project is something that I must do, and I will

When the user clicks on the Add button, a new div should be added as shown in the image above. Implementing this functionality using Bootstrap is crucial because the divs must rearrange correctly based on different resolutions such as 1920x900, 1280x600, ...

Node replication including a drop-down menu

Is there a way to clone a dropdown menu and text box with their values, then append them to the next line when clicking a button? Check out my HTML code snippet: <div class="container"> <div class="mynode"> <span class=& ...

Tips for implementing a nested ng-repeat with nested JSON array data triggered by a button click

Assuming I have assigned the following JSON data to $scope.people: [ { "personId": 1, "name": "Thomas", "age": 39, "friends": [ { "friendId": 1, "nickName": "Lefty" ...

Managing the opening and closing of a Material UI Drawer with a single button/icon in a React Functional Component

I'm looking to create a way to control the opening and closing of the Material UI Drawer using just one button within a React Functional Component. const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { se ...

ensuring the footer is correctly aligned

<div id="footer"> <div class="row"> <div class="span5"> <img src="../goyal/webdesign.jpg" class="verisign-image"></div> I am a <select style="width:10%;" class="dro ...

What is the best way to calculate the overall number of comments per post when using node.js, react js, and sequelize?

Currently, I am working on a project that allows users to ask and answer questions. However, I am facing an issue with the comments field. The comments table displays data correctly and can delete entries, but I need to find a way to count the total number ...

For each item they possess, attach a "!" at the end

Given an array, I am trying to use map to add an exclamation mark to each item in the array. For example: Before - items: ["ball", "book", "pen"] After - items: ["ball!","book!","pen!"] const array = [ { username: "john", team: "red", score: 5 ...

The RC-dock library's 'DockLayout' is not compatible with JSX components. The instance type 'DockLayout' is not a valid JSX element and cannot be used as such

Despite encountering similar questions, none of the provided answers seem to address the issue within my codebase. My project utilizes React 17, Mui v5, and TS v4. I attempted to integrate a basic component from an external package called rc-dock. I simply ...

Executing php class method through ajax with jQuery without requiring a php handler file

How can I trigger a PHP class method using AJAX with jQuery without the need for a separate PHP handler file? Here is my PHP Class animal.php:- <?php class animal { function getName() { return "lion"; } } ?> jQuery code snippet:- ...

Tips on restricting dates to be equal to or earlier:

I have written a code to determine if two given dates are equal or not. The code should allow for the current date to be smaller than or equal to the provided date, but it should not allow for it to be greater. var date = '10-11-2015'; var toda ...