i18n-components
A very small library to help with translations in React
Please report any problems.
Tutorial
Installation
> npm i -s i18n-components
Templates
A list of translations must be created, this uses the template as the key.
const templates = 'Hello, World!': 'en-ZA': 'Howzit!' 'Hello, {0}. The number is {1}.': 'en-ZA': 'The number is {1}, hey {0}.'
Creating a context
Your main component needs to be wrapped. If culture is left off, it will try and get the culture from the browser.
import Translations from 'i18n-components'; { return <Translations = ="en-ZA" > <MyOtherComponents /> </Translations> ; }
Using a translation
import i18n from 'i18n-components'; { return <p>i18n`Hello, World!`</p>; } { const name = 'Jack'; const number setNumber = ; return <div> <p>i18n`Hello, . The number is .`</p> <button ="button" =>+</button> </div> ; }
Should render as
Howzit!
The number is 0, hey Jack.
+
Language fallback
const templates = 'Hello, World!': 'pt': 'Olá Mundo!' 'pt-BR': 'e aí'
Language and culture
{i18n`Hello, World!`}
will return
e aí
Just language
{i18n`Hello, World!`}
will fall back to the language only translation
Olá Mundo!
Fall back to template
{i18n`Hello, World!`}
will fall back to the template because no language can be found.
Hello, World!
Using useI18n Hook
If you want to use a translation in a property you will need to use the hook.
or
{ const hello = useI18n`Hello, World!`; return <input = />;}