How to process/concatenate react-intl message with an EL expression?

3.5k views Asked by At

This code works:

import { MessageResource } from 'react-intl'
.
.
.
<FlatButton label={`(${this.props.patCount})`}> {<MessageResource id="T_DUMMY_VALUE_KEY"/>} </FlatButton>

For ex: if <MessageResource id="T_DUMMY_VALUE_KEY"/> gives string Patients and ${this.props.patCount} gives 10 then the label will turn out to be:

Patients (10)

But my requirement is to bring all the string processing together within label attribute something like this:

    import { MessageResource } from 'react-intl'
    .
    .
    .
    <FlatButton label={<MessageResource id="T_DUMMY_VALUE_KEY"/> + `(${this.props.patCount})`} />

This does not work and gives me output like this:

[OBJECT OBJECT] (10)

Please help.

1

There are 1 answers

0
Prashant On

Check this link for more information.

Message Formatting Fallbacks The message formatting APIs go the extra mile to provide fallbacks for the common situations where formatting fails; at the very least a non-empty string should always be returned. Here's the message formatting fallback algorithm:

Lookup and format the translated message at id, passed to .

  1. Fallback to formatting the defaultMessage.
  2. Fallback to translated message at id's source.
  3. Fallback to defaultMessage source.
  4. Fallback to the literal message id.

Lets say you have one message that has an id: message_one_id And you want to concatenate the second message into it.

Your Messages json file looks like below if you have one. Or I am doing the below example with defaultMessages.

{
  message_one_id: "Unread ({loading})",
  loading: "Loading...",
}

You can use the following method:

<FormattedMessage id="message_one_id"
                  defaultMessage="Unread ({loading})"
                  values={{
                           loading: <FormattedMessage 
                                           id="loading"
                                           defaultMessage="Loading..."
                                    />
                         }}
/>

This will output:

Unread (Loading...)

You can also use this to even dynamically print message:

class NotificationCount extends React.Component {
  constructor(props) {
    this.state = {
                   notification: []
                 };
  }

  componentDidMount() {
    const notifications = [
        {"id": "1", msg: "hello"},
        {"id": "2", msg: "world"}
      ];
    this.setState({notification: notifications});
  }

  render() {
    return (
      <FormattedMessage id="message_one_id"
                        defaultMessage="Unread ({loading})"
                        values={{
                           loading: `${this.state.notification.length}`
                         }}
      />
    );
  }
}

This will output:

Unread (2)