Effortless internationalization for React.js. This library lets you define string translations for an internationalized app, and use them within JSX structures in an easy and flexible way.
import React from 'react';
import * as Intl from 'react-intlstrings';
// Define our strings
Intl.add('en', {
'WELCOME_MSG': 'Hey there, welcome.'
});
Intl.add('es', {
'WELCOME_MSG': 'Hola hola. Bienvenido.'
});
// Create an interface for our app
const Str = Intl.lang('en');
// Use it in react
...
render() {
return (
<div>
<h1><Str id="WELCOME_MSG" /></h1>
</div>
);
}
...
This lib was created to use with React.js specifically. So, there's some added sugar to make things a bit more fun within our app.
You can return JSX structures instead of plain strings:
Intl.add('en', {
LOGIN: <span><strong>Click here</strong> to login</span>
});
Maybe you want a JSX structure that makes some stuff under the hood before returning the result. You can set a stateless component function:
Intl.add('en', {
SELECTED_SHIRT: props => `You've selected a ${props.color} shirt!`
});
...
render() {
return (
<div className="msg"><Str id="SELECTED_SHIRT" color="red" /></div>
);
}
...
What if you want to pass a localized string via props? Or maybe mix it somewhere in a string? The function returned by Intl.lang()
is actually an overloaded function. It works both as a JSX element, and you can also call it directly passing a plain string id. So, you can:
Intl.add('en', {
BUY: 'Buy now',
HINT: 'Click here plz'
});
...
render() {
return (
<a onClick={this.doStuff} title={Str('HINT')}><Str id="BUY" /></a>
);
}
...
If you define your message as a function, JSX props will be passed as the first argument. But, what happens when you want to define a function but you're not calling it via JSX? There's an optional second argument in the plain call to do that.
Intl.add('en', {
CART: props => `You have ${props.count} item${props.count === 1 ? '' : 's'} in your cart`
});
...
render() {
const msg = Str('CART', { count: 5 });
return (
<div>{msg}</div>
);
}
...
That's pretty much of it.
Adds a lang collection just like in the examples.
Convenience function that'll copy a lang and mix it with the new strings
. Useful for partial or slight translations.
Returns an overloaded function that can be used as a React component or called directly to retrieve a translated string in the specified language.
Let's say we store the overloaded function with the name Str
. We can use it in JSX as with any other component. The only required prop is id
(or string
) to pick the message: <Str id="HELLO" />
. Any other prop is passed to the message if it's a function/component, or ignored otherwise.
We can call Str('HELLO')
directly and get our string. If the message was defined as a function, we can pass an optional options object to it, as in Str('HELLO', { example: true })
.
That's all, folks.