0

[React] Tooltip

 2 years ago
source link: http://siongui.github.io/2017/03/06/react-js-tooltip/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[React] Tooltip

March 06, 2017

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

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

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:

[3]reactjs - How to avoid JSX component from condensing when React.js rendering it? - Stack Overflow


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK