sixt-dict
v2.0.43
Published
create translations via context and a HOC to wrap your component
Downloads
4
Readme
Sixt Dict - manage translations with React's context and higher order component (HOC)
The boilerplate for Dict is based on https://github.com/yogaboll/react-npm-component-starter.git by Markus Englund. Thanks for that!
Dict is based on React's context, which is available from React 16.3. First you have to create a phrases object like so:
{
LoginComponent: {
login: 'Please login',
accept: 'Please accept the conditions'
},
DetailsComponent: {
...
}
}
In a React/Redux setup you typically keep it in the store, so any change will immediatly update the displayed phrases. Now you wrap your app into the context provider:
...
import { DictContext } from 'sixt-dict';
const App = createReactClass({
render() {
return (
<div>
<DictContext.Provider value={phrases}>
<Home myvar="foobar" />
</DictContext.Provider>
</div>
);
}
});
The phrases will be passed by the context and update if the source is updated. Now we make dict available as a props. It will offer a function to return a string by it's key. Therefore you wrap your component in the Dict HOC and add the scope (or false):
...
import Dict from 'sixt-dict';
const LoginComponent = props => {
return (
<div>
<p>{props.dict.t('login')}</p>
</div>
);
};
export default Dict(LoginComponent, 'LoginComponent');
How to create a reference to a component that is wrapped in Dict? It's a general problem about HOC's that you loose the reference. Lets say you import a component that is wrapped in the Dict HOC:
...
import MyWrappedComponent from 'MyComponent';
class MyMainComponent extends PureComponent {
constructor(props) {
super(props);
this.ref = null;
}
render() {
return (
<MyWrappedComponent onRef={item => { this.ref = item; }} />
);
}
}
As you can see a little callback can solve the problem, and this.ref will contain the reference.
What replacements are possible so far? Until now I implemented a replacement of multiple placeholders and a smart count. Let's create some phrases:
{
myscope: {
myStringSmartCount: 'I have ${smart_count} suitcase |||| I have ${smart_count} suitcases',
myStringReplacements: 'The ${item1} is nice, but ${item2} is even nicer'
}
}
Then you can use them like:
{props.dict.t('myStringSmartCount', { smart_count: 3 })}
{props.dict.t('myStringReplacements', { item1: 'house', item2: 'castle' })}
It is possible to combine smart_count and simple replacements.
You like it? Use it! Run:
yarn install sixt-dict
and go for it. Make sure you're using at least React 16.3!
Developed with ❤️ by e-Sixt