React-Intl and your multi-lingual application

If you are doing multiple languages in React, then this is the tool you want to use. Here is a quick tutorial on how to use it.

Since you want to allow multiple language everywhere in the app, they have create a wrapper control so that the api is available everywhere.

import { IntlProvider } from 'react-intl'

This library works off of json files that have the key/value pairs that give an id to the text that you want to show. Here is an example of the file that will be required.

{
    "app.get_started_button.title": "Get Started",
    "app.get_previous_button.title": "Previous"
}

You can see that it is a simple json file with only one level. The key is what you will use later to retrieve the text that you want. You will create a new json for each new language that you want to support. You will conditionally load that file based on the language. Now that we have a language file, let use the IntlProvider.

const en = require('./data/en.json')

const App = () => {
    return (
        <IntlProvider messages={en}>
            <MyEntryComponent/>
        </IntlProvider>
    )
}

export default App

Now that we have set up our provider with a file, we can move on to using the provider api. There are a couple of ways to use their api, as a higher order component or as a hook. I using functional components so naturally I use the hooks.

import { useIntl } from 'react-intl'

Now wire the hook in your component.

export default ({  }) => {
    const intl = useIntl()
    return <div/>
}

There are many methods in the intl object, but the one that I am going to show here is formatMessage. formatMessage takes a object with one property: id.

{
   id: 'app.get_started_button.title'
}

The id can be anything you want, but I tend to create a dot separated string based on where the text exists in the app. To wrap it up, all you need to do is pass this object to the formatMessage method.

export default ({  }) => {
    const intl = useIntl()
    return <div>
           {intl.formatMessage({id: 'app.get_started_button.title'})}
           </div>
}

That’s it. Now when you add new language files, you can load them conditionally and pass them to the provider. If you have questions, feel free to reach out to me on Twitter @hivie7510 or email me.

Leave a comment