Search code examples
ruby-on-railsreactjsreact-intlreact-on-rails

react on rails / react intl


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>

    );
  }
}

Solution

  • 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>
    
        );
      }
    }