/
withIntl.js
68 lines (58 loc) · 1.8 KB
/
withIntl.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
import React, {Component, createContext} from 'react';
import hoistNonReactStatics from 'hoist-non-react-statics';
import invariant from 'invariant';
import {invariantIntlContext} from '../utils';
function getDisplayName(Component) {
return Component.displayName || Component.name || 'Component';
}
const IntlContext = createContext(null);
const {Consumer: IntlConsumer, Provider: IntlProvider} = IntlContext;
export const Provider = IntlProvider;
export const Context = IntlContext;
export default function withIntl(WrappedComponent, options = {}) {
const {
intlPropName = 'intl',
forwardRef = false,
// DEPRECATED - use forwardRef and ref on injected component
withRef = false,
enforceContext = true,
} = options;
invariant(
!withRef,
'[React Intl] withRef and getWrappedInstance() are deprecated, ' +
'use forwardRef and set a ref directly on the wrapped component'
);
class withIntl extends Component {
static displayName = `withIntl(${getDisplayName(WrappedComponent)})`;
static WrappedComponent = WrappedComponent;
render() {
return (
<IntlConsumer>
{intl => {
if (enforceContext) {
invariantIntlContext({intl});
}
return (
<WrappedComponent
{...{
...this.props,
[intlPropName]: intl,
}}
ref={forwardRef ? this.props.forwardedRef : null}
/>
);
}}
</IntlConsumer>
);
}
}
if (forwardRef) {
return hoistNonReactStatics(
React.forwardRef((props, ref) =>
React.createElement(withIntl, {...props, forwardedRef: ref})
),
WrappedComponent
);
}
return hoistNonReactStatics(withIntl, WrappedComponent);
}