0

In my application I am using react-alert-template-basic to show alerts. In the API I write the texts directly, like: this.props.alert.error('<some text>');

Now, I want to i18n the text. After a quick search, I found that react-intl is one of the popular choices for that. In the docs I found that the internationalization if performed when rendering, like this:

  <FormattedMessage
                id="welcome"
                defaultMessage={`Hello {name}, you have {unreadCount, number} {unreadCount, plural,
                  one {message}
                  other {messages}
                }`}
                values={{name: <b>{name}</b>, unreadCount}}
            />

I don't know how to use react-intl with react-alert-basic-template. The latter needs the string directly, not the component FormattedMessage.

Does anyone know how to doi it? If not, any other alternative?

Andrés
  • 719
  • 1
  • 4
  • 21

1 Answers1

2

Instead of <FormattedMessage> component, use formatMessage function. You're going to need injectIntl HOC as well:

import React from 'react';
import {injectIntl, FormattedRelative} from 'react-intl';

const Component = ({intl}) => {
  this.props.alert.error(intl.formatMessage(...))

  // your component ...
}


export default injectIntl(Component);

Also, you might consider lingui i18n library if you're at the beginning of your project (I'm the author). It's successor to react-intl and very similar in usage. There's a react tutorial and this example would look like this:

import React from "react"
import { withI18n } from "@lingui/react"

const Component = ({ i18n }) => {
  this.props.alert.error(i18n.t`some text`)

  // your component ...
}

export default withI18n(Component)
Tomáš Ehrlich
  • 6,546
  • 3
  • 25
  • 31
  • I am trying to follow the instructions and I get the next error when executing ``lingui init``: ``ingui-init(1) does not exist, try --help``. Do you know what is happening? – Andrés Aug 17 '18 at 00:13
  • Apart from that, if I have created the message.json manually: `` { "Username": "my username" } `` but what I got after compiling is ``module.exports={languageData:{"plurals":function(n,ord){if(ord)return"other";return n==1?"one":"other"}},mes sages:{"Username":"Username"}}; `` Note how "my username" does not appear in the generated file. What's wrong? – Andrés Aug 17 '18 at 00:32
  • Do you have the latest version installed (2.4.1)? If so, could you please create an issue? https://github.com/lingui/js-lingui/issues/new/choose I tried both (init, compile) and they work as expected. I might need more info. – Tomáš Ehrlich Aug 18 '18 at 03:40