Display the latest tooltip in a Tree view

I have developed a unique custom component to incorporate tooltips for each individual node within a Tree.

function StyledTreeItem(props) {
 const { nodeId, labelText, tooltipTitle, ...other } = props;

 return (
    <Tooltip title={tooltipTitle} placement="left">
        <TreeItem nodeId={nodeId} label={labelText}  {...other} />
    </Tooltip>
 )};

export default function HierarchyTree(props) {

const journeyFilterDataTest = [
    {
        account: ["1551", "4000"],
        campaign: 'DEFECT',
        name: 'XXXX'
    }
]

return (
    <TreeView
        defaultCollapseIcon={<ExpandMoreIcon />}
        defaultExpandIcon={<ChevronRightIcon />}>
        <StyledTreeItem nodeId="1" labelText={journeyFilterDataTest[0].campaign} tooltipTitle="Category">
            <StyledTreeItem nodeId="2" labelText={journeyFilterDataTest[0].name} tooltipTitle="Name" >
                {journeyFilterDataTest[0].account.map(item => {
                    return <StyledTreeItem key={item} nodeId={item} labelText={item} tooltipTitle="Account" />
                })}
            </StyledTreeItem>
        </StyledTreeItem>
    </TreeView>

Encountering an issue where all tooltips become active when hovering over a child node.

Seeking a solution to ensure only the current node being hovered displays the tooltip.

Appreciate any assistance.

Answer №1

your nodeId lacks uniqueness, which is causing the issue. Ensure it is made unique to display only the tooltip of the hovered item. You can check out the sandbox provided here for reference.

  • App.js (example of Tree - iterating through a list of items)
  • assign a unique id of the item as the nodeId for TreeItem
  • utilize a state named parentsClick to monitor the clicked parent tree. If a parent is clicked, only TreeItem without Tooltip will be displayed. If not, all will be displayed.
import React, { useState } from "react";
import "./styles.css";
import { makeStyles } from "@material-ui/core/styles";
import { TreeItem, TreeView } from "@material-ui/lab";
import { Tooltip } from "@material-ui/core";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";

export default function App() {
  const classes = useStyles();
  const [parentsClick, setParentsClick] = useState([]);

  const firstLevel = [
    {
      id: "1",
      label: "Applications",
      secondLevel: [
        { id: "1a", label: "Calendar", thirdLevel: [] },
        { id: "1b", label: "Chrome", thirdLevel: [] },
        { id: "1c", label: "Webstorm", thirdLevel: [] }
      ]
    },
    {
      id: "2",
      label: "Documents",
      secondLevel: [
        { id: "2a", label: "Oss", thirdLevel: [] },
        { id: "2b", label: "Material-UI", thirdLevel: [] }
      ]
    }
  ];

  const StyledTreeItem = (props) => {
    if (parentsClick.includes(props.id))
      return <TreeItem nodeId={props.id} label={props.label} {...props} />;
    else
      return (
        <Tooltip title={props.label} placement="left">
          <TreeItem nodeId={props.id} label={props.label} {...props} />
        </Tooltip>
      );
  };

  return (
    <TreeView
      className={classes.root}
      defaultCollapseIcon={<ExpandMoreIcon />}
      defaultExpandIcon={<ChevronRightIcon />}
    >
      {firstLevel.length > 0 &&
        firstLevel.map((item1stLvl) => (
          <StyledTreeItem
            key={item1stLvl.id}
            id={item1stLvl.id}
            label={item1stLvl.label}
            onClick={() => {
              if (parentsClick.includes(item1stLvl.id))
                setParentsClick(() =>
                  parentsClick.filter((item) => item !== item1stLvl.id)
                );
              else setParentsClick([item1stLvl.id, ...parentsClick]);
            }}
          >
            {item1stLvl.secondLevel.length > 0 &&
              item1stLvl.secondLevel.map((item2ndLvl) => (
                <StyledTreeItem
                  key={item2ndLvl.id}
                  id={item2ndLvl.id}
                  label={item2ndLvl.label}
                />
              ))}
          </StyledTreeItem>
        ))}
    </TreeView>
  );
}

const useStyles = makeStyles({
  root: {
    height: 240,
    flexGrow: 1,
    maxWidth: 400
  }
});

https://i.sstatic.net/8Cs9p.png

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

Create a border around the text using a strokeoutline

I'm attempting to apply an outline to text using CSS. The issue I'm facing is that the shadow doesn't work well for perfectly stroked text. Is there a way to achieve this with just CSS? Below is the code snippet I am currently using: . ...

Create a dynamic HTML design with a resizable left panel and a static right panel. The left panel should not wrap text and display ellipsis if necessary

I am looking to display items in a list with a specific format: |Name | Some other val1| |Very very long no wrap line that...| Some other val2| The right side needs to have a fixed width. The left side should fill al ...

Exploring the intricacies behind the functionality of the spread operator - what

Take a look at this coded function: funtion App(){ const [Cards, setCards] = useState([ {id: 0 , name: 'Harry Potter'}, {id: 1 , name: 'Hermonie Granger'}, {id: 2 , name: 'Ron Weasly'},]) const shuffle = (arr) ...

What is the best way to display a nested Array inside another Array using React?

I'm currently working on a currency converter project where I need to display a list of currencies and their values. Here is an example of the data structure I am receiving from an API using Axios: Object {type: "li", key: "0", ref: null, props: Obje ...

How can I devise an App shell that is stored in cache for a Progressive Web application built with React?

Currently, my React app is bundled into a single JS file using webpack. I am looking for a way to separate the UI shell of my app from the rest of the logic so that the service Worker can cache it. How can I achieve this? This is what my webpack config fi ...

Unexpected Error: Null value prevents accessing 'getElementsByClassName' property in HTML, along with Troubleshooting Inactive Button Behavior in HTML

Can someone identify the error in my HTML code? I keep getting an "Uncaught TypeError: Cannot read property 'getElementsByClassName' of null" error on the second line of the script tag. Additionally, my implemented active header code is not funct ...

Creating an array of JSX elements or HTMLElements in a React TypeScript rendering

Currently in the process of developing a custom bootstrap card wrapper that allows for dynamic rendering of elements on the front and back of the card based on requirements. Here is the initial implementation: import React, { useState, ReactElement } from ...

React: The HTML Details element toggles erratically when initially set to open

I am exploring the use of the HTML <details> tag to create an expandable section with semantic HTML in conjunction with React. The default behavior of <details><summary></summary></details> works well, and for the small perce ...

Transitioning Menus with Submenu Animation

After following a CSS menu tutorial and customizing it, two issues have arisen. When hovering over the "About" menu with additional list links, the transition works but then the content shifts to the left and fades out. The second issue is related to tryin ...

Expanding the navbar with Bootstrap 3.0 by using the navbar-brand class

I'm facing an issue with the navbar-brand while adding my logo. I am using the latest version of bootstrap CSS from getbootstrap.com, and the problem is also evident there: The navbar becomes slightly oversized when the logo is included. However, if I ...

Tips for eliminating the ripple effect when clicking on a q-list item

I have managed to create a sleek sidebar with a curved edge that seamlessly integrates into the body of the page. However, I am struggling to remove the semi-transparent ripple effect that appears when clicking on a list item. The current effect clashes ...

Gliding along a div and concealing it out of view, making it seem like it has disappeared

I attempted to slide down the ".preloader" div after a 2-second delay using JQUERY, but I couldn't get it to work as expected. I didn't want to use a toggle button for this effect. I also experimented with creating an animation using @keyframes, ...

How to Access Nested Arrays in ReactJS

As a ReactJS beginner, I've been making progress with my project. However, I've hit a roadblock that seems to be my final hurdle. Here's what I'm trying to achieve: TV Show - Simpsons Name: Bart Simpson, Gender: Male Name: Homer Simp ...

What are some ways to enhance the appearance of the initial two items in a list through CSS?

Is it possible to enhance the appearance of the first 2 elements in a list using CSS for IE8 compatibility? Here is an example of the format: <ul id="list1" style="margin-left:-20%;font-weight:bold" > <li class="xyz"> Element1 </li> ...

Stealthy Material UI continuing to display components

I am facing a challenge with selectively hiding a material ui component. Initially, my idea was to simply not render the element at all rather than just hiding it based on 'breakpoint' reasons. However, as per the documentation for the mateiral ...

Error TS2339 occurs when attempting to migrate to TypeScript due to the absence of the 'PropTypes' property on the 'React' type

Currently in the process of converting a javascript/react project to a typescript/react/redux project. Encountering an issue with this particular file: import React from 'react'; import GoldenLayout from 'golden-layout'; import {Provi ...

Learn the process of using calc to rotate images on hover with CSS and Jquery

Is there a way to implement the rotate on hover function for images, similar to what is seen on this website under 'our Latest Publications'? I attempted using calc and skew, however, I was unsuccessful in achieving the desired hovering effect o ...

What is the best way to send specific data when the onClick event is triggered in React in this particular

My code contains a loop that iterates through "ScannedCrops" and displays each scanned crop with a button labeled "View More". My goal is to retrieve the id (stored in ScannedCrop._id) and display it using console.log when the user clicks on the button. H ...

Give a radio button some class

<input id="radio1" type="radio" name="rgroup" value="1" > <label for="radio1"><span><span></span></span>1</label> <input id="radio2" type="radio" name="rgroup" value="2" > <label for="radio2"><span ...

Should the element be scrolled beyond a fixed-positioned element

Is there a way to determine if an element is scrolled behind another element that is fixed at the top? I am looking to trigger some javascript when an element is positioned below a fixed element and every height or scrollTop thereafter. I am attempting t ...