Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 886
AnKing Avatar asked Oct 11 '19 17:10

AnKing


People also ask

How do I show tooltip in react?

We use ReactTooltip to render the content of the tooltip. We specify the id property for the tooltip and a content. The place and effect properties define the position of the tooltip. Next, we need to mark an element for which we'd like to display a tooltip.


1 Answers

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

like image 83
Ryan Cogswell Avatar answered Sep 30 '22 20:09

Ryan Cogswell