i18n-components
v1.0.7
Published
I want to try make an easy to use i18n components for react, using tagged template literals.
Downloads
10
Maintainers
Readme
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';
function App()
{
return (
<Translations templates={templates} culture="en-ZA" >
<MyOtherComponents />
</Translations>
);
}
Using a translation
import { i18n } from 'i18n-components';
function SayHi()
{
return (<p>{i18n`Hello, World!`}</p>);
}
function WithVariables()
{
const name = 'Jack';
const [number, setNumber] = useState(0);
return (
<div>
<p>{i18n`Hello, ${name}. The number is ${number}.`}</p>
<button type="button" onClick={() => setNumber(number + 1)}>+</button>
</div>
);
}
Should render as
Language fallback
const templates = {
'Hello, World!': {
'pt': 'Olá Mundo!',
'pt-BR': 'e aí',
},
}
Language and culture
<Translations templates={templates} culture="pt-BR" >
<p>{i18n`Hello, World!`}</p>
</Translations>
will return
Just language
<Translations templates={templates} culture="pt-PT" >
<p>{i18n`Hello, World!`}</p>
</Translations>
will fall back to the language only translation
Fall back to template
<Translations templates={templates} culture="es-ES" >
<p>{i18n`Hello, World!`}</p>
</Translations>
will fall back to the template because no language can be found.
Using useI18n Hook
If you want to use a translation in a property you will need to use the hook.
<input value={useI18n`Hello, World!`} readOnly />
or
function HelloBox()
{
const hello = useI18n`Hello, World!`;
return (<input value={hello} readOnly />);
}