-
Notifications
You must be signed in to change notification settings - Fork 34
/
HeadTag.js
53 lines (43 loc) · 1.24 KB
/
HeadTag.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
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Consumer } from './context';
export default class HeadTag extends React.Component {
state = {
canUseDOM: false,
};
headTags = null;
index = -1;
componentDidMount() {
const { tag, name, property } = this.props;
this.setState({ canUseDOM: true });
this.index = this.headTags.addClientTag(tag, name || property);
}
componentWillUnmount() {
const { tag } = this.props;
this.headTags.removeClientTag(tag, this.index);
}
render() {
const { tag: Tag, ...rest } = this.props;
const { canUseDOM } = this.state;
return (
<Consumer>
{headTags => {
if (headTags == null) {
throw Error('<HeadProvider /> should be in the tree');
}
this.headTags = headTags;
if (canUseDOM) {
if (!headTags.shouldRenderTag(Tag, this.index)) {
return null;
}
const ClientComp = <Tag {...rest} />;
return ReactDOM.createPortal(ClientComp, document.head);
}
const ServerComp = <Tag data-rh="" {...rest} />;
headTags.addServerTag(ServerComp);
return null;
}}
</Consumer>
);
}
}