-
Notifications
You must be signed in to change notification settings - Fork 9
/
portal.jsx
43 lines (34 loc) · 989 Bytes
/
portal.jsx
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
import { Component } from 'react'
import { createPortal } from 'react-dom'
class Portal extends Component {
static idNum = 0
static defaultProps = {
appendTo: document.body,
}
componentWillMount () {
const appendTo = this.props.appendTo
const id = `portal-${Portal.idNum++}`
let element = appendTo.ownerDocument.getElementById(id)
if (!element) {
element = appendTo.ownerDocument.createElement('div')
element.id = id
appendTo.appendChild(element)
}
this._element = element
}
componentWillUnmount () {
const appendTo = this.props.appendTo
// it's possible the element was removed from the dom or the dom has been
// blown away, which will cause `removeChild` to throw an exception
try {
appendTo.removeChild(this._element)
} catch (err) {} // eslint-disable-line no-empty
}
render () {
return createPortal(
this.props.children,
this._element,
)
}
}
export default Portal