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!
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With