Handle translations in component attributes with react-translate-component
span
with the translated string in return. When switching locales through a menu in your app as demonstrated in the docs, labels are updated accordingly. The problem is that you cannot use a component inside of a HTML attribute, for example; directly using Counterpart, the framework-agnostic library underneath the former, works on page load but the automatic update effect is lost, as its translate
method is not called again.The solution is quite simple: force this method to be called again by triggering a state change throughout the app. All we have to do is listen to Counterpart's events in our root component, pretty much like we would with a Flux store:
var React = require('react'),
Counterpart = require('counterpart');
export default class Root extends React.Component
{
constructor()
{
this.state = { locale: Counterpart.getLocale() };
}
onLocaleChange()
{
this.setState({ locale });
}
componentDidMount()
{
Counterpart.onLocaleChange(this.onLocaleChange);
}
componentWillUnmount()
{
Counterpart.offLocaleChange(this.onLocaleChange);
}
render()
{
// ...
}
}
Strings directly processed by Counterpart will now be reevaluated when the locale changes without any extra code.
I am still unsure whether this could become a performance pitfall on a large scale, please feel free to comment about that, or anything else for that matter!