I have a div that I want to make act like a tooltip with reactjs.
<div>on hover here we will show the tooltip</div> <div> <div class="tooltip_custom">this is the tooltip!!</div> </div>
I am used to angularjs using the ng-show
with a condition on the <div>
, I was wondering if there is such binding in reactjs , or else how can I do this functionality ?
Thanks
Tooltip can be shown on Button hover and it can be achieved by setting title attribute.
To show text when hovering over an element in React: Set the onMouseOver and onMouseOut props on the element. Track whether the user is hovering over the element in a state variable. Conditionally render the text based on the state variable.
You can make your component to return the following markup
return ( <div> <div onMouseOver={this.handleMouseIn.bind(this)} onMouseOut={this.handleMouseOut.bind(this)}>on hover here we will show the tooltip</div> <div> <div style={tooltipStyle}>this is the tooltip!!</div> </div> </div> );
Where tooltipStyle
is assigned like this:
const tooltipStyle = { display: this.state.hover ? 'block' : 'none' }
So tooltip depends on component state, now in handleMouseIn
and handleMouseOut
you need to change component state to make tooltip visible.
handleMouseIn() { this.setState({ hover: true }) } handleMouseOut() { this.setState({ hover: false }) }
Here is working example.
You can start diving in React with this article: Thinking in React.
One option is just to do it in CSS. It's not quite as flexible, but with markup like:
<div className="tooltip-on-hover">Hover here</div> <div className="tooltip">This is the tooltip</div>
You could do:
.tooltip { ... visibility: hidden; /* Or display: none, depending on how you want it to behave */ } .tooltip-on-hover:hover + .tooltip { /* Uses the adjacent sibling selector */ visibility: visible; /* Or display: block */ }
Example:
.tooltip { display: none; } .tooltip-on-hover:hover + .tooltip { display: block; }
<div class="tooltip-on-hover">Hover here</div> <div class="tooltip">This is the tooltip</div>
You could also nest the tooltip inside the element so you could use a normal descendant selector like .tooltip-on-hover:hover .tooltip
. You could even use a ::before
or ::after
pseudo-element, there are guides around on how to do this.
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