AnKing
AnKing

Reputation: 2174

Programmatically open Tooltip in Material-UI

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!

Upvotes: 9

Views: 19167

Answers (2)

cr4z
cr4z

Reputation: 581

Ryan's solution works well for when you need to control the open/close state of the tooltip while the user is hovering their cursor over the component. But if you need to ensure it stays open even when the user's cursor leaves, you can accomplish this by passing disableHoverListener as true.

Upvotes: 0

Ryan Cogswell
Ryan Cogswell

Reputation: 80996

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

Upvotes: 14

Related Questions