Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tooltip div with ReactJS

Tags:

objective

I have a div that I want to make act like a tooltip with reactjs.

HTML

<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

like image 247
sisimh Avatar asked Dec 22 '15 20:12

sisimh


People also ask

How do I add tooltip to button react?

Tooltip can be shown on Button hover and it can be achieved by setting title attribute.

How do I show hover text in react?

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.


2 Answers

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.

like image 150
nvartolomei Avatar answered Oct 10 '22 12:10

nvartolomei


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.

like image 29
Inkling Avatar answered Oct 10 '22 11:10

Inkling