You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Jan 10, 2024. It is now read-only.
Tiny React library for implementing gettext localization in your application. It provides HOC function to enhance your application by exposing gettext functions in the context scope.
5
+
A tiny React library that helps to implement internalization in your application using gettext functions. It uses [React Context API](https://reactjs.org/docs/context.html) to expose gettext functions to children components.
6
6
7
7
## Instalation
8
8
9
-
React Gettext requires **React 15.0 or later**. You can add this package using following commands:
9
+
> **Note:** This library requires **React 16.3 or later**
10
10
11
11
```
12
-
npm install react-gettext --save
12
+
npm i react react-gettext
13
13
```
14
14
15
+
## Usage
16
+
17
+
To use this library in your application, you need to do a few simple steps:
18
+
19
+
1. Prepare translations and define plural form functions.
20
+
1. Add `TextdomainContext.Provider` provider to the root of your application.
21
+
1. Updated your components to use context functions, provided by `TextdomainContext`, to translate text messages.
22
+
23
+
Let's take a closer look at each step. First of all, you to create translation catalogs and prepare plural form functions for every language that you are going to use. Each language needs one catalog and one plural form function.
24
+
25
+
The translation catalog is an object that contains key/value pairs where keys are original singular messages and values are translations. If you have a message that can have plural forms, the value for it should be an array with translations where each translation corresponds to appropriate plural form. Finally, if you want to use a context with your messages, then it should be prepended to the message itself and separated by using `\u0004` (end of transition) character. Here is an example:
26
+
27
+
```javascript
28
+
{
29
+
"Hello world!":"¡Hola Mundo!", // regular message
30
+
"article": ["artículo", "artículos"], // plural version
31
+
"Logo link\u0004Homepage":"Página principal", // single message with "Logo link" contex
32
+
"Search results count\u0004article": ["artículo", "artículos"], // plural version with "Search results count" context
33
+
}
15
34
```
16
-
yarn add react-gettext
35
+
36
+
The plural form function is a function that determines the number of a plural form that should be used for a particular translation. For English, the plural form is `n != 1 ? 1 : 0`, that means to use a translation with `0` index when `n == 1`, and a translation with `1` index in all other cases. Slavic and arabic languages have more than 2 plural forms and their functions are more complicated. Translate Toolkit has a [list of plural forms expressions for many languages](http://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html?id=l10n/pluralforms) that you can use in your project. An example of a plural form function can be the following:
37
+
38
+
```javascript
39
+
functiongetPluralForm(n) {
40
+
return n !=1?1:0;
41
+
}
17
42
```
18
43
19
-
## Usage
44
+
The next step is to pass translations and plural form function for the current language to the `buildTextdomain` function. It will create APIs that need to be passed to the `TextdomainContext.Provider` provider that you need to add to the root of your project:
> **Note:** Please, pay attention that you need to avoid passing the results of `buildTextdomain` function directly into `TextdomainContext.Provider`'s value to escape unintentional renders in consumers when a provider’s parent re-renders.
72
+
73
+
Finally, the last step is to update your descendant components to consume these context APIs. Import `TexdomainContext` in the child component and assign it to the component `contextType` static properly. It will expose gettext APIs to that component via `this.context` field:
To make it translatable you need to update your `app.js` file to use HOC function and export higher-order component:
135
+
To make it translatable, you need to update your `app.js` file to use TextdomainContext provider and build textdomain using messages list and plural form function:
60
136
61
137
```diff
62
138
// app.js
63
139
import React, { Component } from 'react';
64
-
+ import withGettext from 'react-gettext';
140
+
+ import { TextdomainContext, buildTextdomain } from 'react-gettext';
65
141
import Header from './Header';
66
142
import Footer from './Footer';
67
143
68
-
- export default class App extends Component {
69
-
+ class App extends Component {
70
-
...
71
-
}
144
+
export default class App extends Component {
145
+
146
+
+ constructor(props) {
147
+
+ super(props);
148
+
+ this.state = {
149
+
+ textdomain: buildTextdomain(
150
+
+ {
151
+
+ 'Welcome to my application!': 'Bienvenido a mi aplicación!',
152
+
+ // ...
153
+
+ },
154
+
+ n => n != 1
155
+
+ ),
156
+
+ };
157
+
+ }
72
158
73
-
+ export default withGettext({...}, 'n != 1')(App);
After doing it you can start using `gettext`, `ngettext`, `xgettext` and `nxgettext` functions in your descending components:
77
174
78
175
```diff
79
176
// Header.js
80
-
- import React, { Component } from 'react';
81
-
+ import React, { Component } from 'react';
82
-
+ import PropTypes from 'prop-types';
177
+
import React, { Component } from 'react';
178
+
+ import { TextdomainContext } from 'react-gettext';
83
179
84
180
export default class Header extends Component {
85
181
86
182
render() {
183
+
+ const { gettext } = this.context;
87
184
return (
88
185
- <h1>Welcome to my application!</h1>
89
-
+ <h1>{this.context.gettext('Welcome to my application!')}</h1>
186
+
+ <h1>{gettext('Welcome to my application!')}</h1>
90
187
);
91
188
}
92
189
93
190
}
94
191
95
-
+ Header.contextTypes = {
96
-
+ gettext: PropTypes.func.isRequired,
97
-
+ ngettext: PropTypes.func.isRequired,
98
-
+ xgettext: PropTypes.func.isRequired,
99
-
+ nxgettext: PropTypes.func.isRequired,
100
-
+ };
192
+
+ Header.contextType = TextdomainContext;
101
193
```
102
194
103
-
See an [example](https://github.com/eugene-manuilov/react-gettext/tree/master/examples) application to get better understanding how to use it.
195
+
Check a [sample](https://github.com/eugene-manuilov/react-gettext/tree/master/examples/poedit) application to see how it works.
Higher-order function which is exported by default from `react-gettext` package. It accepts two arguments and returns function to create higher-order component.
110
-
111
-
-**translations**: a hash object or a function which returns hash object where keys are original messages and values are translated messages.
112
-
-**pluralForms**: a string to calculate plural form (used by [Gettext PO](http://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html?id=l10n/pluralforms)) or a function which accepts a number and calculates a plural form number. Pay attentions that plural forms are zero-based what means to get 1st plural form it should return 0, to get 2nd - 1, and so on.
113
-
-**options**: a hash object with options. Currently supports following options:
114
-
-**withRef**: an optional boolean flag that determines whether or not to set `ref` property to a wrapped component what will allow you to get wrapped component instance by calling `getWrappedComponent()` function of the HOC. By default: `FALSE`.
115
-
116
-
Example:
117
-
118
-
```javascript
119
-
consttranslations= {
120
-
'Some text':'Some translated text',
121
-
...
122
-
};
199
+
### buildTextdomain(translations, pluralForm)
123
200
124
-
constpluralForms='(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)'; // 3 plural forms for Russian, Belarusian, Bosnian, Croatian, Serbian, Ukrainian, etc.
201
+
Builds gettext APIs for TextdomainContext provider that will work with provided translations.
One more alternative is to not create HOC, but use Textdomain component directly. You can import it using `import { Textdomain } from 'react-gettext'` and use it as a regular component which will provide context functions to translate your messages. Just don't forget to pass `translations` and `plural` props to this component when you render it.
166
-
167
-
168
212
### gettext(message)
169
213
170
214
The function to translate a string. Accepts original message and returns translation if it exists, otherwise original message.
The initial version of this library had been created when React used the legacy version of Context APIs, thus it played a keystone role in the main approach of how to use this library at that time. However, in the late March of 2018, React 16.3 was released and that API became deprecated, so do the main approach used in this library.
273
+
274
+
The proper way to use this library is described in the [Usage](#usage) section, this section contains legacy API that will be removed in next versions of the library. We don't encourage you to use it in a new project.
Higher-order function which is exported by default from `react-gettext` package. It accepts two arguments and returns function to create higher-order component.
279
+
280
+
-**translations**: a hash object or a function which returns hash object where keys are original messages and values are translated messages.
281
+
-**pluralForms**: a string to calculate plural form (used by [Gettext PO](http://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html?id=l10n/pluralforms)) or a function which accepts a number and calculates a plural form number. Pay attentions that plural forms are zero-based what means to get 1st plural form it should return 0, to get 2nd - 1, and so on.
282
+
-**options**: a hash object with options. Currently supports following options:
283
+
-**withRef**: an optional boolean flag that determines whether or not to set `ref` property to a wrapped component what will allow you to get wrapped component instance by calling `getWrappedComponent()` function of the HOC. By default: `FALSE`.
284
+
285
+
Example:
286
+
287
+
```javascript
288
+
consttranslations= {
289
+
'Some text':'Some translated text',
290
+
...
291
+
};
292
+
293
+
constpluralForms='(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)'; // 3 plural forms for Russian, Belarusian, Bosnian, Croatian, Serbian, Ukrainian, etc.
One more alternative is to not create HOC, but use Textdomain component directly. You can import it using `import { Textdomain } from 'react-gettext'` and use it as a regular component which will provide context functions to translate your messages. Just don't forget to pass `translations` and `plural` props to this component when you render it.
335
+
226
336
## Poedit
227
337
228
-
If you use Poedit app to translate your messages, then you can use `gettext;ngettext:1,2;xgettext:1,2c;nxgettext:1,2,4c` as keywords list to properly parse and extract strings from your javascript files.
338
+
If you want to use Poedit application to translate your messages, then use the following keywords to properly extract static copy from your javascript files:
229
339
230
-
Here is an example of a **POT** file which you can start with:
Here is an example of a **POT** file that you can use as a starting point:
231
345
232
346
```
233
347
msgid ""
@@ -246,7 +360,8 @@ msgstr ""
246
360
"X-Poedit-SourceCharset: UTF-8\n"
247
361
```
248
362
249
-
If you prefer using npm script, please add this to your package.json file. Make sure correct `project path` and `output` path is set.
363
+
If you prefer using npm scripts, then you can add the following command to your `package.json` file to extract static copy and generate POT file using CLI commands. Make sure, you have correct `project` and `output` paths.
0 commit comments