forked from lingui/js-lingui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathI18n.js
60 lines (50 loc) · 1.48 KB
/
I18n.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
// @flow
import * as React from "react"
import PropTypes from "prop-types"
export default class I18n extends React.Component<*, *> {
static defaultProps = {
update: true,
withHash: true
}
static contextTypes = {
linguiPublisher: PropTypes.object
}
componentDidMount() {
const { subscribe } = this.getI18n()
if (this.props.update && subscribe) subscribe(this.checkUpdate)
}
componentWillUnmount() {
const { unsubscribe } = this.getI18n()
if (this.props.update && unsubscribe) unsubscribe(this.checkUpdate)
}
// Test checks that subscribe/unsubscribe is called with function.
checkUpdate = /* istanbul ignore next */ () => {
this.forceUpdate()
}
getI18n() {
return this.context.linguiPublisher || {}
}
render() {
const { children, withHash } = this.props
const { i18n, i18nHash } = this.getI18n()
const props = {
i18n,
// Add hash of active language and active catalog, so underlying
// PureComponent is forced to rerender.
...(withHash ? { i18nHash } : {})
}
if (typeof children === "function") {
return children(props)
}
if (process.env.NODE_ENV !== "production") {
console.warn(
"I18n accepts only function as a children. " +
"Other usecases are deprecated and will be removed in v3.0"
)
}
// Deprecate v3.0
return React.isValidElement(children)
? React.cloneElement(children, props)
: React.createElement(children, props)
}
}