ReactJS :: Internationalization

For global websites, internationalization (i18n) is vital to engage local audiences. For client-side libraries like React, the only option used to be to serve slow, bulky libraries to handle things like translation and number formatting. More recently, the native Intl API has been made available in browsers to avoid the heavy download cost.

A library by the Yahoo team called React Intl helps bring this new API to React projects. A special set of components automatically translate strings and format numbers, dates and currency. It forms part of its collection of i18n tools called FormatJS.

<FormattedDate value={new Date()} weekday='long' />

Advertisement

Each component takes props that mirror the settings available to the Intl API. By supplying the required format of the date, the API can use what it knows about the locale of the browser to compute a string. Any time any of these props change, the string updates automatically.

<FormattedMessage
    id='homepage.greeting'
    description='Main greeting for the homepage'
    defaultMessage='Welcome!'
/>

String translations require adding an appropriate translation to the messages prop to the provider at the root of the application, but which can be used throughout the application. The library detects the ID and replaces the content as necessary. Details of all the options in this feature can be found here.

Leave a Reply

Your email address will not be published. Required fields are marked *

*