Sometimes, we want to add a tooltip div with React and JavaScript.
In this article, we’ll look at how to add a tooltip div with React and JavaScript.
How to add a tooltip div with React and JavaScript?
To add a tooltip div with React and JavaScript, we can add event handlers for the mouseover and mouseout events.
For instance, we write:
import React from "react";
export default function App() {
const [hover, setHover] = React.useState();
const handleMouseIn = () => {
setHover(true);
};
const handleMouseOut = () => {
setHover(false);
};
const tooltipStyle = {
display: hover ? "block" : "none"
};
return (
<div>
<div onMouseOver={handleMouseIn} onMouseOut={handleMouseOut}>
hover
</div>
<div>
<div style={tooltipStyle}>this is the tooltip!!</div>
</div>
</div>
);
}
We define the hover
state to keep track of when we hover over the ‘hover’ div.
Then we add the handleMouseIn
and handleMouseOut
functions to call setHover
to true
and false
respwectively.
Then we add the mouseover and mouseout event handler to the div with `hover’ in it so that when we hover over it, the tooltip div will show.
We set onMouseOver
to handleMouseIn
and onMouseOut
to handleMouseOut
to add the handlers.
Next, we add the tooltip div by adding a div with the style
prop set to tooltipStyle
.
We set the display
CSS property to 'block'
if hover
is true
and false
otherwise to show the tooltip when we hover over ‘hover’.
Conclusion
To add a tooltip div with React and JavaScript, we can add event handlers for the mouseover and mouseout events.