2

I am trying to implement i18n for a rails/react_on_rails project following this guide; https://github.com/shakacode/react_on_rails/blob/master/docs/basics/i18n.md

I get the error "formatMessage is not defined", so I am probably missing something, here is my code:

import PropTypes from 'prop-types';
import React from 'react';
import { IntlProvider } from 'react-intl';

import { addLocaleData } from 'react-intl';
import en from 'react-intl/locale-data/en';
import nb from 'react-intl/locale-data/nb';
import { translations } from '../../../libs/i18n/translations';
import { defaultLocale } from '../../../libs/i18n/default';

// Initizalize all locales for react-intl.
addLocaleData([...en, ...nb]);

// set locale and messages for IntlProvider.
// const locale = method_to_get_current_locale() || defaultLocale;
const locale = defaultLocale;
const messages = translations[locale];

import { defaultMessages } from '../../../libs/i18n/default';


export default class TextMessage extends React.Component {

  render() {
    return (
      <IntlProvider locale={locale} key={locale} messages={messages}>   
        { formatMessage(defaultMessages.ActionsYes) }
      </IntlProvider>

    );
  }
}

1 Answer 1

1

You get the exact error message:

formatMessage is not defined

I've been using react-intl so what I believe you need to do is first to inject intl object. You can read about it in the react-intl documentation. Try this:

import { IntlProvider, injectIntl } from 'react-intl';

...

class TextMessage extends React.Component {


  render() {

    return (
      <IntlProvider locale={locale} key={locale} messages={messages}>
        { this.props.intl.formatMessage(defaultMessages.ActionsYes) }
      </IntlProvider>

    );
  }
}

export default injectIntl(TextMessage);

I bet it will work.

Or even simpler just change this:

import { IntlProvider, FormattedMessage } from 'react-intl';

...

export default class TextMessage extends React.Component {
  render() {
    return (
       <IntlProvider locale={locale} key={locale} messages={messages}>
        <FormattedMessage {...defaultMessages.ActionsYes} />
       </IntlProvider>

    );
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Small followup here, using the last version I get an error again; Failed prop type: The prop id is marked as required in FormattedMessage, but its value is undefined.
You need to pass id and defaultMessage prop to FormattedMessage. make console.log(defaultMessages.ActionsYes) and check if it has them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.