forked from tvkhoa/react-tippy
-
Notifications
You must be signed in to change notification settings - Fork 3
/
component.js
114 lines (92 loc) · 2.33 KB
/
component.js
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import tippy from 'tippy.js/dist/tippy.standalone.js';
const defaultProps = {
title: null,
open: false,
disabled: false
};
function applyIfFunction( fn ) {
return (typeof fn === 'function') ? fn() : fn;
}
class Tooltip extends Component {
componentDidMount() {
this.initTippy();
}
componentWillUnmount() {
this.destroyTippy();
}
componentDidUpdate(prevProps) {
if ( !this.tippy )
return;
// enable and disabled
if (this.props.disabled === false && prevProps.disabled === true) {
this.tippy.enable();
return;
}
if (this.props.disabled === true && prevProps.disabled === false) {
this.tippy.disable();
return;
}
// open
if (this.props.open === true && !prevProps.open) {
setTimeout(() => {
this.showTooltip();
}, 0)
}
if (this.props.open === false && prevProps.open === true) {
this.hideTooltip();
}
}
showTooltip = () => {
this.tippy.show();
}
hideTooltip = () => {
this.tippy.hide();
}
contentRoot = () => {
if ( !this._contentRoot && typeof window === 'object' )
this._contentRoot = window.document.createElement( 'div' );
return this._contentRoot;
}
initTippy = () => {
this.tooltipDOM.setAttribute('title', this.props.title);
tippy(this.tooltipDOM, {
...this.props,
html: this.props.render ? this.contentRoot() : this.props.rawTemplate,
dynamicTitle: true,
performance: true
});
this.tippy = this.tooltipDOM._tippy;
if (this.props.open) {
this.showTooltip();
}
}
destroyTippy = () => {
this.tippy.destroy();
this.tippy = null;
}
render() {
return (
<div
ref={(tooltip) => { this.tooltipDOM = tooltip; }}
title={this.props.title}
className={this.props.className}
tabIndex={this.props.tabIndex}
style={{
display: 'inline',
...this.props.style
}}
>
{this.props.children}
{this.props.render && this.contentRoot()
? ReactDOM.createPortal(
applyIfFunction( this.props.render ),
this.contentRoot() )
: null}
</div>
);
}
}
Tooltip.defaultProps = defaultProps;
export default Tooltip;