reactlang.js
v1.0.22
Published
React.js localization component highly inspired by Laravel's Lang
Downloads
6
Maintainers
Readme
Installation
Different installation methods:
- Yarn:
yarn add reactlang.js
- NPM:
npm install reactlang.js
- Manually: Download latest release
Documentation
How to Use
const lang = {
common: {
hello_world: 'Hello, world!'
}
};
<Translatable
lang={lang}
content={{
transKey: 'common.hello_world'
}}
/>
Will render the following:
<span>Hello, world!</span>
With children
const lang = {
common: {
first_name: 'First name'
}
};
<Translatable
lang={lang}
attributes={{
placeholder: {
transKey: 'common.first_name'
}
}}
>
<input type="text" />
</Translatable>
Will render the following:
<input type="text" placeholder="First name" />
Messages source format
The messages source format should look like the following:
{
name: {
key1: 'value1',
key2: 'value2',
// ... and more key-value pairs.
},
name: {
key1: 'value1',
key2: 'value2',
// ... and more key-value pairs.
},
// ... and more locales.
}
Properties
The component MUST receive the lang
property AND either a content
property OR an attributes
property.
You can also add a reference
property that accepts a function that will receive the translated string.
This is handy for using the translated string outside of the render method.
e.g.
class HelloWorld extends Component {
bindTranslation = translatedString => {
this.translation = translatedString;
}
render() {
return (
<div>
<Translatable
lang={lang}
content={{
transKey: 'common.hello_world'
}}
reference={this.bindTranslation}
/>
</div>
);
}
}
lang
(Required)
An object matching the Messages source format like below:
{
common: {
home: 'Home',
about: 'About',
contact: 'Contact'
},
search: {
filter: 'Filter',
price_range: 'Price Range'
}
}
content
(Optional)
An object containing any of the following properties (transKey is required):
{
transKey: 'common.people_lower',
count: 5,
replacements: {
number: 5
}
}
attributes
(Optional)
An object with element attributes as keys with object values containing the same properties as the content
property (transKey is required):
{
placeholder: {
transKey: 'common.select'
}
}
id
(Optional)
An id to be applied to the span rendered by the component when no children are present.
className
(Optional)
A class name string.
handleError
(Optional)
A function for handling errors. Receives an object like the following:
{
message: 'The Translatable component only allows a single child',
name: 'Too many children'
}
Development
- Fork this repository and clone it.
- Create a branch from develop:
git checkout -b feature/xxxxxxx
- Submit a PR to be merged into develop branch.
Testing
To run the tests use the following commands:
- Single run:
npm run test
- Run on changes:
npm run test:watch