Sometimes, we want to create a tooltip div with React.
In this article, we’ll look at how to create a tooltip div with React.
Create a Tooltip Div with React
To create a tooltip div with React, we can set the onMouseOver
and onMouseOut
props to functions that set the hover state to true
and false
respectively.
And we can use the hover state to determine whether the tooltip div is displayed.
For instance, we can write:
import { useState } from "react";
export default function App() {
const [hover, setHover] = useState();
return (
<div>
<div
onMouseOver={() => setHover(true)}
onMouseOut={() => setHover(false)}
>
Hover
</div>
<div>
<div style={{ display: hover ? "block" : "none" }}>
this is the tooltip!!
</div>
</div>
</div>
);
}
We have the hover
state that we created with the useState
hook.
Then we add the onMouseOver
and onMouseOut
props to set hover
to true
and false
respectively when those events are emitted on the outer div.
Next, we add the tooltip div by writing:
<div style={{ display: hover ? "block" : "none" }}>
this is the tooltip!!
</div>
Now when we hover over the Hover
text, we see the tooltip displayed.
Conclusion
To create a tooltip div with React, we can set the onMouseOver
and onMouseOut
props to functions that set the hover state to true
and false
respectively.
And we can use the hover state to determine whether the tooltip div is displayed.