8

I need to be able to add a tooltip to the element so it functions like normal (opens up when element is hovered) and at the same time I need an ability to open it up programmatically.

I know it has open prop that allows to do so, but in this case I will be switching component from uncontrolled to controlled and this isn't possible.

I'm also unable to sumulate :hover event on a button inside tooltip because this is impossible in browser.

Is there a way to accomplish this maybe thru refs? When I use ref with tooltip it just being passed over to the child element.

Thanks!

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198
AnKing
  • 1,994
  • 6
  • 31
  • 54

1 Answers1

11

When the Tooltip is controlled, the onOpen and onClose functions will still fire at the times when it would open/close the tooltip in the uncontrolled case. You can use these functions to change the controlled state of the Tooltip.

Working example:

import React from "react";
import ReactDOM from "react-dom";

import Tooltip from "@material-ui/core/Tooltip";
import Button from "@material-ui/core/Button";

function App() {
  const [tooltipIsOpen, setTooltipIsOpen] = React.useState(false);
  return (
    <div className="App">
      <Tooltip
        open={tooltipIsOpen}
        onOpen={() => setTooltipIsOpen(true)}
        onClose={() => setTooltipIsOpen(false)}
        title="I'm a controlled tooltip"
      >
        <span>Hover over me or click the button</span>
      </Tooltip>
      <div style={{ marginTop: 50 }}>
        <Button
          onClick={() => setTooltipIsOpen(!tooltipIsOpen)}
          variant="contained"
          color="primary"
        >
          Click me to {tooltipIsOpen ? "close" : "open"} the tooltip
        </Button>
      </div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit controlled Tooltip

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198