FormatJS

Full tutorial with example code can be found on our blog.

Check blog post about FormatJS and React application localization.

Check also FormatJS CLI integration docs to integrating i18n keys extraction.

Install dependencies

Add react-intl library to your newly created project.

# Using NPM
npm i -S react react-intl

# Using yarn
yarn add react react-intl

react-intl configuration

Create configuration like below:

import React from "react";
import {IntlProvider} from 'react-intl'
import LanguageContext from "./LanguageContext";

class SimpleLocalize extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      messages: undefined,
      language: "en"
    };
  }

  componentDidMount() {
    this.setupLanguageMessages(this.state.language);
  }

  setupLanguageMessages = (language) => {
    const projectToken = "5e13e3019cff4dc6abe36009445f0883";
    const translationsUrl = `https://cdn.simplelocalize.io/${projectToken}/_latest/${language}`;
    return fetch(translationsUrl)
      .then((data) => data.json())
      .then((messages) => this.setState({language, messages}));
  };

  render() {
    return (
      <LanguageContext.Provider
        value={{
          changeLanguage: (language) => this.setupLanguageMessages(language)
        }}>
        <IntlProvider
          locale={this.state.language}
          messages={this.state.messages}>
          {this.state.messages ? this.props.children : null}
        </IntlProvider>
      </LanguageContext.Provider>
    )
  }
}

export default SimpleLocalize;

Wrap main component

Wrap your application with created SimpleLocalize component to provide translations for React application.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import SimpleLocalize from "./SimpleLocalize";

ReactDOM.render(
    <SimpleLocalize>
      <App/>
    </SimpleLocalize>,
  document.getElementById('root')
);

FormattedMessage usage

<FormattedMessage id="YOUR_TRANSLATION_KEY"/>

React will convert FormattedMessage tag into span tag and put concrete translation into it. You can also use <FormattedHTMLMessage id="TRANSLATION_WITH_CSS"/> which will also produce message with HTML inside span tag. Example translation key could look like following:

TRANSLATION_WITH_CSS = This is my <strong>text</strong>

Switching between languages

Use LanguageContext.Consumer to switch languages.

 <LanguageContext.Consumer>
      {context => (<div className="App">
            <button onClick={() => context.changeLanguage("en")}>English</button>
            <button onClick={() => context.changeLanguage("es")}>Spanish</button>
      </div>)}
 </LanguageContext.Consumer>

Full application code is available on Github. Visit simplelocalize/simplelocalize-react-intl repository.