-
Notifications
You must be signed in to change notification settings - Fork 21
/
FormattedMessage.jsx
45 lines (41 loc) · 1.41 KB
/
FormattedMessage.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
import React from 'react';
import PropTypes from 'prop-types';
import { TextContext } from './TextProvider';
const FormattedMessage = (props) => (
<TextContext.Consumer>
{(context) => {
/**
* We get the text to be injected from react's context. Here its TextContext
*/
const { id, values, alt, ...restProps } = props;
/* eslint-disable-next-line react/destructuring-assignment */
let messageString = Object.prototype.hasOwnProperty.call(context, id) ? context[id] : alt;
/**
* Iterate through all the keys given as the prop and replace with corresponding values.
*/
Object.keys(values).forEach((key) => {
messageString = messageString.replace(`{${key}}`, values[key]);
});
/* Do not frown over this, many a times you need to do this, like :
* https://github.com/yahoo/react-intl/blob/master/src/components/html-message.js#L86
*/
const style = {
fontSize: 'inherit',
};
/* eslint-disable react/no-danger */
return (
<span style={style} dangerouslySetInnerHTML={{ __html: messageString }} {...restProps} />
);
}}
</TextContext.Consumer>
);
FormattedMessage.propTypes = {
id: PropTypes.string.isRequired,
values: PropTypes.objectOf(PropTypes.string),
alt: PropTypes.string,
};
FormattedMessage.defaultProps = {
values: {},
alt: '',
};
export { FormattedMessage as default };