[React] Tooltip


See demo first. Move the cursor (mouse pointer) to hover over the blue text with underline:

Demo

The idea comes from the JavaScript implementation of my post [1]. The following is complete React source code.

HTML:

<div id="root">
  <!-- This div's content will be managed by React. -->
</div>

CSS:

style.css | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
span[data-descr] {
    text-decoration: underline;
    color: blue;
    cursor: help;
}

.invisible {
    display: none;
}

.tooltip {
    position: absolute;
    background-color: yellow;
    border: 1px gray solid;
    border-radius: 3px;
    padding: 3px;
}

JSX:

app.jsx | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function Tooltip(props) {
  if (props.isVisible) {
    return <div className="tooltip" style={props.style}>{props.textContent}</div>;
  }
  return <div className="tooltip invisible" style={props.style}>{props.textContent}</div>;
}

class TooltipApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isShowTooltip: false,
      tooltipContent: "",
      tooltipStyle: {}
    };
    this.ShowTooltip = this.ShowTooltip.bind(this);
    this.HideTooltip = this.HideTooltip.bind(this);
  }

  ShowTooltip(event) {
    var elm = event.target;
    var tTop = (elm.offsetTop + elm.offsetHeight + 5) + 'px';
    var tLeft = elm.offsetLeft + 'px';
    this.setState({
      isShowTooltip: true,
      tooltipContent: event.target.dataset.descr,
      tooltipStyle: {
        top: tTop,
        left: tLeft
      }
    });
  }

  HideTooltip() {
    this.setState({isShowTooltip: false});
  }

  render() {
    return (
      <div>
        <Tooltip style={this.state.tooltipStyle} textContent={this.state.tooltipContent} isVisible={this.state.isShowTooltip} />
        <p>This is a example of{" "}
          <span onMouseEnter={this.ShowTooltip} onMouseLeave={this.HideTooltip} data-descr="Hello, I am tooltip!">tooltip</span> via{" "}
          <span onMouseEnter={this.ShowTooltip} onMouseLeave={this.HideTooltip} data-descr="Hello, I am React!">React</span></p>
      </div>
    );
  }
}

ReactDOM.render(
  <TooltipApp />,
  document.getElementById('root')
);

Tested on: CodePen


References:

[1]Pure CSS Tooltip and JavaScript Implementation
[2]
[3]reactjs - How to avoid JSX component from condensing when React.js rendering it? - Stack Overflow