i18n
In this chapter we will add internationalization support to the previously written CommentForm
.
Table of Contents
- Spotting the locale strings
- Moving the strings into the i18n package
- Integrating the i18n package into our container
Spotting the locale strings
If we take a look at our markup that we've pasted into our CommentForm
container, we will see that we currently only have one string to locale, the submit button label Create comment
.
const CommentForm = (props: PropsType) => {
return (
<form>
<input name="id" type="text"/>
<input name="postId" type="text"/>
<input name="mail" type="text"/>
<input name="name" type="text"/>
<input name="body" type="text"/>
<input type="submit" value="Create comment"/>
</form>
);
};
Usually you would also want to locale strings for the placeholders, labels for the inputs and more, but our example contains only one string.
Moving the strings into the i18n package
The mono-repository contains a dedicated i18n
package located at packages/my-fancy-ui-i18n
. Since all packages follow the same structure let's jump right into our entry point source file at src/index.js
. This file exposes a singleton instance of node-polyglot
which provides us the slim i18n API to use. You will also spot that we declare default phrases which we import from the en-US.js
file.
Open up the file and you will see that we declared two exports by default. We structure our i18n files based upon the apps structure, so in our case we would need to add a new object property to the comments
export, e.g.
// ... Pre-Existing translatables ...
export const comments = {
// ... Pre-Existing translatables ...
form: {
submit: 'Create comment'
}
};
Integrating the i18n package into our container
After adding our translatable, let's integrate the usage of the node-polyglot
API in our React codebase.
// ... other types and imports ...
import i18n from '@company-scope/my-fancy-ui-i18n';
const CommentForm = (props: PropsType) => {
return (
<form>
<input name="id" type="text"/>
<input name="postId" type="text"/>
<input name="mail" type="text"/>
<input name="name" type="text"/>
<input name="body" type="text"/>
<input type="submit" value={i18n.t('comments.form.submit')}/>
</form>
);
};
// ... connect HOC configuration and exports ...
The only changes that we made was to do was to import the package and to replace the static string with the interpolated i18n.t('comments.form.submit')
, that's it!