This repository has been archived by the owner on May 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 167
/
Base.jsx
97 lines (87 loc) · 2.53 KB
/
Base.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
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
import React from 'react';
import PropTypes from 'prop-types';
import { I18nProvider, i18nLoader } from 'terra-i18n';
import './baseStyles';
const propTypes = {
/**
* The component(s) that will be wrapped by `<Base />`.
*/
children: PropTypes.node.isRequired,
/**
* The locale name.
*/
locale: PropTypes.string.isRequired,
/**
* Customized translations provided by consuming application only for current locale.
*/
/* eslint-disable consistent-return */
customMessages: (props, propName, componentName) => {
if (Object.keys(props[propName]).length !== 0 && props.locale === undefined) {
return new Error(`Missing locale prop for ${propName} in ${componentName} props`);
}
},
/**
* Activates [React Strict Mode](https://reactjs.org/docs/strict-mode.html) for descendants
*/
strictMode: PropTypes.bool,
/**
* The component(s) that will be wrapped by `<Base />` ONLY
* in the event that translations have not been loaded yet.
* NOTE: Absolutely no locale-dependent logic should be
* utilized in this placeholder.
*/
translationsLoadingPlaceholder: PropTypes.node,
};
const defaultProps = {
customMessages: {},
strictMode: false,
};
class Base extends React.Component {
constructor(props) {
super(props);
this.state = {
areTranslationsLoaded: false,
locale: props.locale,
messages: {},
};
}
componentDidMount() {
if (this.props.locale !== undefined) {
try {
i18nLoader(this.props.locale, this.setState, this);
} catch (e) {
// eslint-disable-next-line no-console
console.error(e);
}
}
}
componentDidUpdate(prevProps) {
if (this.props.locale !== undefined && this.props.locale !== prevProps.locale) {
try {
i18nLoader(this.props.locale, this.setState, this);
} catch (e) {
// eslint-disable-next-line no-console
console.error(e);
}
}
}
render() {
const {
children,
customMessages,
strictMode,
translationsLoadingPlaceholder,
} = this.props;
const messages = { ...this.state.messages, ...customMessages };
const renderChildren = strictMode ? (<React.StrictMode>{children}</React.StrictMode>) : children;
if (!this.state.areTranslationsLoaded) return <div>{translationsLoadingPlaceholder}</div>;
return (
<I18nProvider locale={this.state.locale} messages={messages}>
{renderChildren}
</I18nProvider>
);
}
}
Base.propTypes = propTypes;
Base.defaultProps = defaultProps;
export default Base;