Skip to content

A component for React that utilizes the Counterpart module provide multi-lingual/localized text content.

License

Notifications You must be signed in to change notification settings

tobitos/react-translate-component

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

29 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React Translate Component

Translate is a component for React that utilizes the Counterpart module and the Interpolate component to provide multi-lingual/localized text content. It allows switching locales without a page reload.

Installation

Install via npm:

% npm install react-translate-component

Usage

Here is a quick-start tutorial to get you up and running with Translate. It's a step-by-step guide on how to build a simple app that uses the Translate component from scratch. We assume you have recent versions of Node.js and npm installed.

First, let's create a new project:

$ mkdir translate-example
$ cd translate-example
$ touch client.js
$ npm init                   # accept all defaults here

Next, add a dependency to our Translate component:

$ npm install react-translate-component --save

This also installs React and Counterpart because these are configured as a peer dependencies.

We will put our application logic into client.js. Open the file in your favorite editor and add the following lines:

'use strict';

var counterpart = require('counterpart');
var React       = require('react');
var Translate   = require('react-translate-component');

This loads the localization library, React and our Translate component.

Let's write our entry-point React component. Add the following code to the file:

var MyApp = React.createClass({
  displayName: 'MyApp',

  render: function() {
    return (
      React.DOM.html(null,
        React.DOM.head(null,
          React.DOM.meta({ charSet: 'utf-8' }),
          React.DOM.title(null, 'React Translate Quick-Start'),
          React.DOM.script({ src: '/bundle.js' })
        ),

        React.DOM.body(null,
          '--> body content will be added soon <--'
        )
      )
    );
  }
});

if (typeof window !== 'undefined') {
  window.onload = function() {
    React.renderComponent(MyApp(), document);
  };
}

module.exports = MyApp;

Now we have the basic HTML chrome for our tiny little app.

Next, we will create a LocaleSwitcher component which will be used to, well, switch locales. Here is the code to append to client.js:

var LocaleSwitcher = React.createClass({
  handleChange: function(e) {
    counterpart.setLocale(e.target.value);
  },

  render: function() {
    return (
      React.DOM.p(null,
        React.DOM.span(null, 'Switch Locale: '),

        React.DOM.select(
            { 
              defaultValue: counterpart.getLocale(), 
              onChange:     this.handleChange
            }, 
          React.DOM.option(null, 'en'),
          React.DOM.option(null, 'de')
        )
      )
    );
  }
});

For demonstration purposes, we don't bother and hard-code the available locales.

Whenever the user selects a different locale from the drop-down, we correspondingly set the new drop-down's value as locale in the Counterpart library, which in turn triggers an event that our (soon to be integrated) Translate component listens to. As initially active value for the select element we specify Counterpart's current locale ("en" by default).

Now add LocaleSwitcher as child of the empty body element of our MyApp component:

        React.DOM.body(null,
          LocaleSwitcher()
        )

Next, we create a Greeter component that is going to display a localized message which will greet you:

var Greeter = React.createClass({
  render: function() {
    return this.transferPropsTo(
      Translate(null, 'example.greeting')
    );
  }
});

In the component's render function, we simply transfer all incoming props to Translate (the component this repo is all about). As its only child we specify the string "example.greeting" which acts as the key into the translations dictionary of Counterpart.

Now add the new Greeter component to the body element, provide a name prop holding your first name and a component prop which is set to React.DOM.h1:

        React.DOM.body(null,
          LocaleSwitcher(),
          Greeter({ name: 'Martin', component: React.DOM.h1 })
        )

The value of the name prop will be interpolated into the translation result. The component prop tells Translate which HTML tag to render as container element (a <span> by default).

All that's left to do is to add the actual translations. You do so by calling the registerTranslations function of Counterpart. Add this to client.js:

counterpart.registerTranslations('en', {
  example: {
    greeting: 'Hello %(name)s! How are you today?'
  }
});

counterpart.registerTranslations('de', {
  example: {
    greeting: 'Hallo, %(name)s! Wie geht\'s dir heute so?'
  }
});

In the translations above we defined placeholders (in sprintf's named arguments syntax) which will be interpolated with the value of the name prop we gave to the Greeter component.

That's it for the application logic. To eventually see this working in a browser, we need to create the server-side code that will be executed by Node.js.

First, let's install some required dependencies and create a server.js file:

$ npm install express connect-browserify --save
$ touch server.js

Now open up server.js and add the following lines:

'use strict';

var express     = require('express');
var browserify  = require('connect-browserify');
var render      = require('react').renderComponentToString;
var App         = require('./client');

express()
  .use('/bundle.js', browserify.serve({
    entry: __dirname + '/client',
    debug: true, watch: true
  }))
  .get('/', function(req, res, next) {
    res.send(render(App()));
  })
  .listen(3000, function() {
    console.log('Point your browser to http://localhost:3000');
  });

Note that you shouldn't use this code in production as the bundle.js file will be compiled on every request.

Last but not least, start the application:

$ node server.js

It should tell you to point your browser to http://localhost:3000. There you will find the page greeting you. Observe that when switching locales the greeting message adjusts its text to the new locale without ever reloading the page or doing any ajax magic.

Please take a look at this repo's spec.js file to see some more nice tricks. To become a master craftsman we encourage you to also read Counterpart's README.

An Advanced Example

The code for a more sophisticated example can be found in the repo's example directory. You can clone this repository and run make install example and point your web browser to http://localhost:3000. In case you are too lazy for that, we also have a live demo of the example app on Heroku.

Contributing

Here's a quick guide:

  1. Fork the repo and make install.

  2. Run the tests. We only take pull requests with passing tests, and it's great to know that you have a clean slate: make test.

  3. Add a test for your change. Only refactoring and documentation changes require no new tests. If you are adding functionality or are fixing a bug, we need a test!

  4. Make the test pass.

  5. Push to your fork and submit a pull request.

Licence

Released under The MIT License.

About

A component for React that utilizes the Counterpart module provide multi-lingual/localized text content.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%