react-translated
A dead simple way to add complex translations (i18n) in a React (DOM/Native) project.
Features
- ? Data interpolation
- ☄ Component interpolation
- Ⓜ Markdown inline-manipulations
- ? Custom manipulations, pluralizations, and grammar rules based on input-data
- ⚛ Component-level translation files (enables loading only required translations)
Example
Write this:
To render this:
Support
React DOM and React Native ?
Try
Play around with the library in your browser through the CodeSandbox.
Table of Contents
Installation
Whatever floats your boat:
Setup
Step 1: Create the translations file
Create a file that will contain a mapping of keys to the string in each language you support.
To keep things simple, use the strings of your default language as the key:
NOTE: There is no enforcement on the key used for a language. In these examples, 2-digit country codes (
en
,fr
, etc) are used. Decide on a convention and use that for all translations.
Step 2: Connect the Provider
Wrap your top-level component with the <Provider>
and set the translation
and language
props:
NOTE: The value of the
language
prop must be one of the keys used for a language defined in Step 1.
Step 3: Start translating
That is all!
Continue reading below to see how to handle the various translation scenarios.
Usage
The library can be imported in whatever way you find suitable:
Or:
Translate
vs Translator
The Translate
component should always be used when the translation is rendered as a child component; such as buttons, paragraphs, headings, etc.
The Translator
component should only be used when the translation is needed as a string; such as placeholders, alternate text, etc.
Translation scenarios
- Static text
- Templated text
- Dynamically templated text
- Styled text
- Component within text
- Translated text as string (for text input placeholders)
Static text
This is pretty self-explanatory:
Renders as:
Templated text
To use dynamic text, the text can be templated:
Renders as:
Dynamically templated text
Sometimes just dynamic text is not enough and the template itself needs to be dynamic (for example pluralization). That can be achieved using a function call:
Renders as:
Since these templates are simple function calls, things more complex than pluralization can be done too:
Renders as:
Styled text
The translated text can also have some basic styling applied:
Renders as:
And of course the same can be done with dynamic templates:
Renders as:
Component within text
For more advanced uses where Markdown and Emojis don’t suffice, components can be rendered within the text:
Renders as:
Another practical application of this is nested translations - text that requires data that also needs to be translated:
Renders as:
Translated text as string
Added v2.2.0
In scenarios where the translated text is required as a string, such as with text inputs placeholders or accessibility labels, the Translator
can be used:
Renders as: