Search code examples
reactjsmaterial-uihovertooltipstoppropagation

stopPropagation for Material UI Tooltip


Need to e.stopPropagation() for child in the Parent container. Both of them are wrapped into Material Ui Tooltip. I get displayed both tooltips if Hover over Child. onOpen={e => e.stopPropagation()} not helping

      <Tooltip title="main container">
        <Button style={{ background: "red", color: "white" }}>
          <Tooltip title="child container">
            <Button
              style={{ background: "green", color: "white" }}
            >
              Child
            </Button>
          </Tooltip>
        </Button>
      </Tooltip>

Solution

  • You can manually trigger opening the tooltips by handling onMouseEnter and onMouseLeave events on both your parent and child buttons and hide parent's tooltip if child's state is opened like this:

    import { useState } from "react";
    import { Button, Tooltip } from "@mui/material";
    
    export default function App() {
      const [parentOpen, setParentOpen] = useState(false);
      const [childOpen, setChildOpen] = useState(false);
    
      return (
        <div>
          <Tooltip
            title="main container"
            open={!childOpen && parentOpen}
            disableHoverListener
          >
            <Button
              style={{ background: "red", color: "white" }}
              onMouseEnter={() => setParentOpen(true)}
              onMouseLeave={() => setParentOpen(false)}
            >
              <Tooltip
                title="child container"
                open={childOpen}
                disableHoverListener
              >
                <Button
                  style={{ background: "green", color: "white" }}
                  onMouseEnter={() => setChildOpen(true)}
                  onMouseLeave={() => setChildOpen(false)}
                >
                  Child
                </Button>
              </Tooltip>
            </Button>
          </Tooltip>
        </div>
      );
    }
    

    You can take a look at this sandbox for a live working example of this usage.